2013-11-01 44 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