do while循环不能有两个cin语句? [英] do while loops can't have two cin statements?

查看:142
本文介绍了do while循环不能有两个cin语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是遵循一个简单的c ++教程do / while循环,我似乎已经复制了本教程中写的是什么,但我不会得到相同的结果。这是我的代码:

I'm just following a simple c++ tutorial on do/while loops and i seem to have copied exactly what was written in the tutorial but i'm not yielding the same results. This is my code:

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语句,程序工作正常..

Right now, after 1 iteration, the loop just runs without asking for my inputs again and only calculating the sum with my first initial input for i. However if i remove the second pair of cout/cin statements, the program works fine..

有人可能发现我的错误吗?

can someone spot my error please? thank you!

推荐答案

如果更改

int str;

char str;

您的循环按照您的意图工作(在Visual Studio 2010中测试)。

虽然,你也应该检查 str =='n',因为他们告诉你他们已经完成了。

Your loop works as you seem to intend (tested in Visual Studio 2010).
Although, you should also probably check for str == 'n', since they told you that they were done.

这篇关于do while循环不能有两个cin语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆