while 循环不能有两个 CIN 语句吗?

do while loops can't have two cin statements?

本文关键字:CIN 两个 语句 不能 循环 while      更新时间:2023-10-16

我只是在遵循一个简单的 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;
}