2013-11-01 43 views
2

按文件的新生產線,直到結束程序打印具有讀取整數列表,並打印出來,因爲它是當我們按下輸入最多endoffile(或Ctrl + C)閱讀整數,在C++

前:

1 2 3 4 
1 2 3 4 
3 1 2 4 
3 1 2 4 

while(cin.get()!=-1){ 
       i=0;     
       while(1) { 
         if(cin.get()=='\n') { 
           break; 
         } 
         else { 
           cin >> a[i]; 
           i++; 
         } 
       } 
       for(k=0;k<i;k++) { 
         cout << a[k]<< " "; 
           } 
       } 

,但它不是給第一個整數,原來的輸出如下

例如:

1 2 3 4 
2 3 4 
3 1 2 4 
1 2 4 

如何改進此代碼以讀取並打印第一個整數。

感謝提前:)

+0

出了什麼問題只是'的std :: string線; while(std :: getline(std :: cin,line)){std :: cout << line << std :: endl; }'。它不檢查非數字,但是如果輸入不是數字,你就不會說程序應該做什麼。 –

回答

2

cin.get()讀取從標準輸入一個字符並返回它。您不會將cin.get()的返回值分配給變量。因此,剛剛讀取的值會丟失。

+0

有什麼辦法可以保存它嗎? – hanugm

+0

把它放到一個變量中。 – Oswald

+0

做:char c; if((c = cin.get())=='\ n') –

1

除了忽略get()的結果,如果輸入包含無效字符 (如果cin >> a [i]失敗),您的代碼將在無限循環中結束 。

#include <cctype> 
#include <iostream> 
#include <sstream> 

int main() 
{ 
    std::cout << "Numbers: "; 
    { 
     std::string line; 
     if(std::getline(std::cin, line)) { 
      std::istringstream s(line); 
      int number; 
      while(s >> number) { 
       std::cout << number << ' '; 
      }; 
      // Consume trailing whitespaces: 
      s >> std::ws; 
      if(! s.eof()) { std::cerr << "Invalid Input"; } 
      std::cout << std::endl; 
     } 
    } 
    std::cout << "Digits: "; 
    { 
     std::istream::int_type ch;; 
     while((ch = std::cin.get()) != std::istream::traits_type::eof()) { 
      if(isdigit(ch)) std::cout << std::istream::char_type(ch) << ' '; 
      else if(isspace(ch)) { 
       if(ch == '\n') 
        break; 
      } 
      else { 
       std::cerr << "Invalid Input"; 
       break; 
      } 
     }; 
     std::cout << std::endl; 
    } 
    return 0; 
} 
1

你可以讀整行然後解析它。其中一個變種(最小修改您的代碼)低於:

#include <iostream> 
#include <sstream> 

using namespace std; 

int main(int argc, char *argv[]) { 
    int i, k; 
    char a[1024] = {0}; 
    string str; 
    while(cin.good()){ 
    i=0; 
    getline(cin, str); 
    stringstream ss(str); 
    while (ss >> a[i]) { if (++i > 1024) break; } 
    for(k=0;k<i;k++) { 
     cout << a[k] << " "; 
    } 
    cout << endl; 
    } 
} 

輸出:

g++ -o main main.cpp ; echo -ne " 1 2 3 4\n5 6 7 8\n"|./main 
1 2 3 4 
5 6 7 8