do while loops can't have two cin statements?

自古美人都是妖i 提交于 2019-12-23 22:32:58

问题


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);
}

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!


回答1:


If you change

int str;

to

char str;

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.




回答2:


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.

The usual cure is to put something like cin.ignore(100, '\n'); after you read the string. The 100 is more or less arbitrary -- it just limits the number of characters it'll skip.




回答3:


...and only calculating the sum with my first initial input for i...

This is an expected behavior, because you are just reading the str and not using it. If you enter i >= 15 then loop must break, otherwise continues.



来源:https://stackoverflow.com/questions/10802157/do-while-loops-cant-have-two-cin-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!