我只是遵循一个关于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次迭代后,循环运行,而无需再次询问我的输入,仅使用我的第一个初始输入来计算总和。
但是,如果我删除第二对cout / cin语句,则该程序可以正常工作。
有人可以发现我的错误吗?谢谢!
最佳答案
如果你改变
int str;
至
char str;
您的循环可以按预期工作(在Visual Studio 2010中测试)。
虽然,您也应该检查
str == 'n'
,因为他们告诉您已经完成了。关于c++ - while循环不能有两个cin语句吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10802157/