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

How to input stream by cin for more than 2 variable

本文关键字:变量 输入流 2个 何通过 cin      更新时间:2023-10-16

我对C++流有问题。我需要输入一些数字,程序应该比较"字符串"并标记为"const"grove"等。主要问题是当我不知道有多少用户想要输入时,如何输入这些数字。我认为最好的想法是使用-1作为结束的最后一个"标识符"。但是如何一个接一个地输入这些数字(digital1[space]digital2[space]Digital3[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

对不起我的英语。问候

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

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

试试这个:

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

我脑海中第一件事:

  1. 将整行作为字符串读取
  2. 使用带空格的strtok作为分隔符
  3. strtok将以字符串形式返回每个数字,每次输入时调用atoi

这可能不是最优雅的解决方案,但它很有效,您不需要在最后输入"-1"或任何内容。只需输入空格分隔的数字,点击回车键即可完成(直观的输入方式)。