2017-04-18 41 views

回答

0

如果你只是想從這樣的一行訪問整數,一種方法是簡單地繼續閱讀整數,而你可以。

如果出於某種原因,您發現整數讀取失敗(例如,因爲輸入流中有{),請跳過該單個字符並繼續。

此示例代碼:

#include <iostream> 

int main() { 
    int intVal;        // for getting int 
    char charVal;       // for skipping chars 
    while (true) { 
     while (! (std::cin >> intVal)) {  // while no integer available 
      std::cin.clear();    // clear fail bit and 
      if (! (std::cin >> charVal)) { // skip the offending char. 
       return 0;     // if no char left, end of file. 
      } 
     } 
     std::cout << intVal << '\n';   // print int and carry on 
    } 
    return 0; 
} 

解說詞如下:

pax> echo '{(314159,271828),(42,-1)}' | ./testprog 
314159 
271828 
42 
-1 
+0

那只是真棒!我正在玩它,以適應我的代碼,因爲我必須翻譯成矩陣!謝謝,非常感謝,我不知道你可以像(!(std :: cin >> intVal))來測試它是一個整數還是一個char! 再次!謝謝!! –

相關問題