2015-11-07 77 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 
    } 
}