【问题标题】:while loop that doesn't wait for cin不等待 cin 的 while 循环
【发布时间】:2012-05-20 11:56:11
【问题描述】:

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

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 << ':';
}

它只是垃圾邮件“成分名称:数量:成分名称:数量:...”等等

【问题讨论】:

  • 即EOF,其他错误等。一般情况下,您必须检查程序中的返回码
  • 我的错,ing 是一个字符串。
  • 发布最简单的情况,您可以在其中复制此内容。可能只是 while(ing != "0") { cout > ing; } 将是你的情况。
  • stdin 没有被重定向,是吗?标准输入可能来自管道或完全分离,在这种情况下它不会等待。
  • 很可能,quant 是数字,而您输入的不是数字。您必须检查您的直播状态。

标签: c++ loops while-loop


【解决方案1】:

不确定fil 是什么。

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

【讨论】:

  • @Yoan 如果您在这段代码之前使用 cin,您甚至可能必须在 之前 进行这些检查。
【解决方案2】:

我刚刚尝试了这段代码,没有任何问题(Visual Studio 2008)。请发布更多您的代码,我会尽力提供帮助。

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

【讨论】:

  • bool addRecipe() { string name, temp, ing;字符 tmp;整数; fstream fil("Recipes.dmr", ios::in|ios::app); cout > 名称; for(int i = 0; i > temp) { if(temp == name) { cerr
猜你喜欢
  • 2015-07-18
  • 2010-12-26
  • 1970-01-01
  • 2016-12-05
  • 2016-07-22
  • 2017-06-21
  • 2021-08-14
  • 2012-10-13
相关资源
最近更新 更多