如何通过cin为2个以上的变量输入流

时间:2015-11-07 00:32:25

标签: c++

我遇到了C ++流的问题。我需要输入一些数字,程序应该比较“字符串”并标记为“const”“grove”等。主要问题是当我不知道有多少用户想要输入时如何输入这些数字。我认为最好的想法是使用-1作为结尾的最后一个“标识符”。但是如何逐个输入这些数字(digit1 [space] digit2 [space] digit3 [space] -1)?我试着这样做

int main() {

    int repeatCount = 0;
    int stringCount = 0;
    float digit1 = 0;
    float digit2 = 0;

    cout << "How many strings You have?" << endl;
    cin >> iloscPowtorzen;

    while(stringCount != repeatCount)
    {
        cin >> digit2 >> digit2;
        while (digit2 != -1)
        {
            //HERE I HAVEN'T GOT ANY IDEA
        }
        stringCount++;
    }

    system("pause");
    return 0;
}

示例(应该如何工作):

输入

<<How many strings You have?
>>3
>>1 1 1 1 -1
>>1 2 3 4 -1
>>4 3 2 1 -1

输出

<<const
<<grove
<<decrease

抱歉我的英文。 此致

3 个答案:

答案 0 :(得分:0)

我想到了第一件事:

  1. 以字符串形式阅读整行。
  2. 以空格作为分隔符使用strtok
  3. strtok将以字符串形式返回每个数字,在每个输入上调用atoi
  4. 这可能不是最优雅的解决方案,但它可以工作,您不需要在结尾处输入“-1”或任何内容。只需输入空格分隔的数字,按Enter键即可完成(直观的输入方式)。

答案 1 :(得分:0)

试试这个:

while (true)
{
  float curNum;
  cin >> curNum;
  if (!cin)
    break;
  // do your logic here
}

答案 2 :(得分:0)

一次阅读一个,而不是成对阅读。否则,它会将下一行的第一个数字读入第二个变量。

for (stringCount = 0; stringCount < repeatCount; stringCount++) {
    while (true) {
        cin >> digit2;
        if (digit2 == -1) {
            break; // get out of while loop
        }
        cin >> digit1;
        // do stuff with digit1 and digit2
    }
}