我只是遵循一个关于 do/while 循环的简单 C++ 教程,我似乎已经完全复制了教程中编写的内容,但我没有得到相同的结果。这是我的代码:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}
现在,经过 1 次迭代后,循环将运行,而无需再次询问我的输入,并且仅计算 i 的第一个初始输入的总和。
但是,如果我删除第二对 cout/cin 语句,程序就可以正常工作。
有人可以发现我的错误吗?谢谢你!
After you read the string with your cin >> str;
, there's still a new-line sitting in the input buffer. When you execute cin >> i;
in the next iteration, it reads the newline as if you just pressed enter without entering a number, so it doesn't wait for you to enter anything.
通常的治疗方法是放一些类似的东西cin.ignore(100, '\n');
读取字符串后。这100
或多或少是任意的——它只是限制了它要跳过的字符数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)