2014-07-06 34 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