涉及getline()和循环的C++问题
C++ problems involving getline() and a loop
我正在做一项学校作业,现在我正把头撞在墙上,试图弄清楚为什么我的程序没有像我希望的那样运行!
int main(){
string input;
char choice;
bool getChoice(char);
string getInput();
CharConverter newInput;
do{
cout << "Please enter a sentence.n";
getline(cin, input);
cout << newInput.properWords(input) << endl;
cout << newInput.uppercase(input) << endl;
cout << "Would you like to do that again?n";
cin >> choice;
} while (getChoice(choice) == true);
return 0;
}
这个程序在第一轮中运行良好,但当getChoice()==true时,我遇到了一个问题,do-while块第二次循环。在第二个循环中,程序要求我再次输入一个句子,但随后跳到"你想再输入一次吗?",而不允许用户输入或输出properWords()和uppercase()函数的结果。我怀疑getline有一些我不理解的地方,但我还没有通过谷歌搜索找到它。有人帮忙吗?
编辑:我原来的解释有一个错误。
这是因为用getline
读取输入与逐字符读取输入不能很好地混合。当您输入Y
/N
字符以指示是否要继续时,也可以按enter。这会将n
放入输入缓冲区,但>>
不会从中获取它。当您调用getline
时,n
就在那里,所以函数会立即返回一个空字符串。
要解决此问题,请将choice
设为std::string
,使用getline
读取它,并将第一个字符发送给getChoice
函数,如下所示:
string choice;
...
do {
...
do {
getline(cin, choice);
} while (choice.size() == 0);
} while (getChoice(choice[0]));
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题