【发布时间】:2015-01-19 20:04:19
【问题描述】:
我打算编写一个程序,它会简单地从用户输入的输入中删除单个字母,假设我们有一些文本,例如:“猴子吃香蕉”,我们应该从上面的文本中删除字母“a” .
最终的输出应该是这样的: '猴子等 bnn'
我的代码可以完美地处理单个字符串,但是我必须使用 getline() 函数来获取更长的文本,这就是为什么我必须声明字符串数组,以便传递它的大小在 getline() 函数的第二个参数中,如下所示:
string text[256];
getline(text, 256);
我想使用 getline() 函数而不给出数组的大小,但我认为这是不可能的,因此我需要坚持使用字符串数组而不是字符串。
我遇到的问题是我不知道如何正确传递字符串数组,以将其用作函数的参数。这是我的代码;
#include <iostream>
#include <string>
using namespace std;
void deleteLetter(string &text[], char c)
{
size_t positionL = text.find(c);
if(positionL == string::npos)
cout << "I'm sorry, there is no such letter in text" << endl;
else
text.erase(positionL, positionL);
cout << "After your character removed: " << text << endl;
}
int main()
{
string str1[256];
char a = 'a';
cin.getline(str1, 256);
deleteLetter(str1, a);
}
我知道这是基本的东西,但我仍然无法自己解决。 Perhpahs 我应该寻求你的帮助。
【问题讨论】:
-
使用
std::vector< std::string >而不是数组;传递给函数更容易。 -
另外,在传递数组时不要忘记传递数组的容量和元素个数。当您传递一个数组时,没有函数可以确定数组中的容量或项数。
-
cin.getline在 C 字符串(字符数组)上运行,而不是在std::string上运行。我猜你想要的是独立的getline函数:getline(cin, str),它在std::string上运行 - 然后将它放在一个循环中以读取多行直到结束:while(getline(cin, str)) { deleteLetter(str, a); } -
@ThomasMatthews 只要您不想修改 容器,使用
std::string*或类似array_view<std::string>作为函数参数类型可能是更好的选择:它不需要用户使用特定的容器。
标签: c++ arrays string function