2014-07-06 55 views
1

我正在使用下面的代码来解析文件。分析文件时输出错误?

std::string line; 
std::ifstream infile("C:\\t50_20_1.td"); 

int num; 
int pred; 
int succ; 

while (std::getline(infile, line)) 
{ 
    std::istringstream iss(line); 
    while(iss >> num || !iss.eof()) { 
     if(iss.fail()) { 
      iss.clear(); 
      continue; 
     } else { 
      std::cout<<num<<std::endl; 
     } 
    } 
    std::cin.ignore(); 
} 

我想打印的所有数字在以下文件

50 
1 35 11 3 13  10 5  11 2  19 1  21 10  23 2  26 3  29 6  35 5  42 10  44 5  
2 3 12 8 7  15 12  19 9  24 6  27 13  29 7  32 8  34 6  35 8  37 9  38 12  39 9  
3 19 7 4 15  8 2  10 7  15 12  21 11  26 9  36 10  
4 35 8 5 13  7 7  10 8  13 13  20 1  21 5  44 1  48 15  

但在程序结束时,我只得到一个数作为输出

50 
+1

步骤通过与调试器的代码。注意你用'endl << flush'连续两次刷新流。 – chris

+0

'while(iss >> num ||!iss.eof())'看起来不正确 –

+0

注意'<< std :: flush'是多余的'<< std :: endl'已经这样做了。 –

回答

1

我建议你删除因为在while循环中不是必需的,所以条件是!iss.eof()。必须按下Enter键才能继续解析以下行。请参阅下面的代码。另外,我建议你添加“using namespace std”,这意味着std ::必要时可以使代码更具可读性。最后,你声明的一些变量没有被实际使用,所以它们已经从下面的代码中删除。

#include <fstream> 
#include <iostream> 
#include <sstream> 

using namespace std; 

int main (int argc, char ** argv) 
{ 
    string line = ""; 
    ifstream infile("C:\\t50_20_1.td"); 
    int num = 0; 

    while (getline(infile, line)) 
    { 
     istringstream iss(line); 
     while(iss >> num) { 
      if(iss.fail()) { 
       iss.clear(); 
       continue; 
      } else { 
       cout << num << endl; 
      } 
     } 
     std::cin.ignore(); 
    } 
    return 0; 
} 

样本输出(选择的输出只,所有数字正在与上面的代码输出)

50 
... 
44 
5 
... 
39 
9 
... 
48 
15