为什么它重复 5 次
Why it repeats 5 times?
本文关键字:为什么 更新时间:2023-10-16
void firstSentence(void){
string incorrectSentence;
string correctSentence = "I have bought a new car";
cout << "Your sentence is: I have buy a new car" << endl;
cout << "Try to correct it: ";
cin >> incorrectSentence;
if(incorrectSentence == correctSentence){
cout << "Goosh. Your great. You've done it perfectly.";
}
else{
firstSentence();
}
}
这是我尝试在我的程序中调用的函数。但是我被困住了,很生气,因为我自己找不到解决方案。它的作用是,如果"if 语句"中的条件为真,则我的输出不是我预期的。输出重复 5 次"尝试纠正它。你的句子是:我买了一辆新车..
为什么它正好重复 5 次等等,那里发生了什么,为什么它不起作用?
这个:
cin >> incorrectSentence;
不读取行,而是读取以空格分隔的标记。如果您的输入是正确的句子,这意味着第一次它将读取"I"
,而句子的其余部分保留在输入流中。程序正确确定"I"
与"I have bought a new car"
、循环和读取不同,"have"
第二次。这也与正确的句子不同,因此它再次循环并读取"bought"
.这一直持续到从流中读取所有内容,此时cin >> incorrectSentence;
再次阻止。
解决方案是使用
getline(cin, incorrectSentence);
。读一行。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 为什么 std::unique 不调用 std::sort?
- 既然存在危险,为什么项目要使用-I include开关
- 为什么在运行时没有向我们提供有关分段错误的更多信息?