删除字母代码出错(C ++)

时间:2015-12-23 03:05:02

标签: c++ string char

我正在编写下面的代码,假设从用户那里获取信息(一个句子)并删除所需的字母。但是,它仅在该句子是一个单词时才有效。如果信息包含空格,它将在空格处终止。任何建议,如何让程序读取整个句子?

#include <iostream>
#include <string>
#include <algorithm>


using namespace std;

int main() {
string sentence;
char letterRemoved;

//Entering in Information
cout <<"Enter a sentence here!";
cin >> sentence;

cout <<"Enter letter to remove";
cin>>letterRemoved;

//Removing Occurence of letter
sentence.erase(remove(sentence.begin(), sentence.end(),letterRemoved), sentence.end());

//Print out
cout<<sentence << "\n";

return 0;
}

1 个答案:

答案 0 :(得分:4)

使用cin >> sentence读取输入只读取直到遇到空格,然后停止。如果您想要读取整行(直到用户按下回车键),您想使用std::getline

getline(cin, sentence);

或者,如果您希望在找到完整停止字符或换行符之前进行阅读,则可以使用delimeter参数getline

getline(cin, sentence, '.');