while loop that doesn't wait for cin

蹲街弑〆低调 提交于 2019-12-08 05:38:17

问题


quick question: why wont this while-loop wait for input? (ing is a string)

while(ing != "0")

{
    cout << "Ingredient name: ";
    cin >> ing;
    for(int i = 0; i < ing.length(); i++)
    {
        if(ing[i] == ' ')
        ing[i] = '#';
    }
    fil << ing << ':';
    cout << "Quantity: ";
    cin >> quant;
    fil << quant << ':';
}

it just spamms "ingredient name: quantity: ingredient name: quantity: ..." and so on


回答1:


Not sure what fil is.

I think your problem is that you need to flush the stream with a cin.ignore() at the bottom of the loop (or else do a cin.getline() to get your input). Otherwise the newline at the end of the input (when you press enter to submit the input) gets saved for the next cin which is your cin >> ing. So the newline gets used up there and doesn't actually ask the user for new input.




回答2:


I just tried this code out I'm having no problems (Visual Studio 2008). Please let post more of your code and I'll do my best to help.

// CinProblem.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <tchar.h>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string ing;
    stringstream fil;
    int quant = 0;

    while(ing != "0")
    {
        cout << "Ingredient name: ";
        cin >> ing;
        for(int i = 0; 
            i < (int)ing.length(); 
            i++)
        {
            if(ing[i] == ' ')
            ing[i] = '#';
        }
        fil << ing << ':';
        cout << "Quantity: ";
        cin >> quant;
        fil << quant << ':';
    }

    system("pause");

    return 0;
}


来源:https://stackoverflow.com/questions/10558934/while-loop-that-doesnt-wait-for-cin

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