不等待cin的while循环

不等待cin的while循环

本文介绍了不等待cin的while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题:为什么这个while循环不等待输入?(ing是一个字符串)

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

推荐答案

不确定fil是什么.

我认为您的问题是您需要在循环的底部使用cin.ignore()刷新流(或者执行cin.getline()来获取输入).否则,输入末尾的换行符(当您按Enter提交输入时)将保存到下一个cin(即您的cin >> ing)中.因此,换行符在那里用完了,实际上并没有要求用户提供新的输入.

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.

这篇关于不等待cin的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:23