while 循环不能有两个 CIN 语句吗?
do while loops can't have two cin statements?
我只是在遵循一个简单的 c++ 教程,关于 do/while 循环,我似乎完全复制了教程中写的内容,但我没有产生相同的结果。这是我的代码:
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语句,程序可以正常工作。
有人可以发现我的错误吗?谢谢!
用cin >> str;
读取字符串后,输入缓冲区中仍然有一个换行符。当您在下一次迭代中执行cin >> i;
时,它会读取换行符,就好像您只是按 Enter 而不输入数字一样,因此它不会等待您输入任何内容。
通常的治疗方法是在读取字符串后放入类似cin.ignore(100, 'n');
的东西。100
或多或少是任意的——它只是限制了它将跳过的字符数。
如果您更改
int str;
自
char str;
您的循环按照您的预期工作(在 Visual Studio 2010 中测试)。
虽然,您可能还应该检查 str == 'n'
,因为他们告诉您他们已经完成了。
。并且仅计算我的第一个初始输入的总和...
这是预期的行为,因为您只是在阅读str
而不使用它。如果输入i >= 15
则循环必须断开,否则将继续。
我想你想要这个东西
在这种情况下,总和c
将小于 15,如果用户输入 y,则继续求和。
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char 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 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- Cin 需要两个输入
- 两个 cin / cout 语句合并为一个
- 当我使用 cin 进行两个输入时,如何接受一个输入
- 两个输入C++来自 Bash 的 cin
- 当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了
- 使用cin.ignore()跳过两个空间
- 在C 中使用两个GetLine(CIN,S)
- CIN为什么将浮动值分为两个部分
- 具有两个cin的无限循环
- 连续两个"cin"不起作用
- while 循环不能有两个 CIN 语句吗?
- 如何在c++中使用两个cin语句
- 从cin读取两个字符串并将其写回时出现意外行为
- 辛:等<ENTER>着。两个继续 cin.忽略不起作用