2015-11-07 76 views
0

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

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 

对不起,我的英语水平。 问候

+1

什么是'iloscPowtorzen'?应该是'repeatCount'? – Barmar

回答

0

第一关事关我的脑海:

  1. 阅读整行作为一个字符串。
  2. 使用strtok并以空格作为分隔符。
  3. strtok将以字符串形式返回每个数字,在每个输入上调用atoi

这可能不是最优雅的解决方案,但它可以工作,并且不需要在末尾输入“-1”或任何内容。只需输入空格分隔的数字,按回车即可完成(直观的输入方式)。

0

试试这个:

while (true) 
{ 
    float curNum; 
    cin >> curNum; 
    if (!cin) 
    break; 
    // do your logic here 
} 
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 
    } 
}