2011-08-30 112 views
-1

我想讀取文本文件並顯示數據。問題是while循環沒有結束,也沒有顯示任何東西。怎麼了?讀取文本文件並在C++中顯示數據

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <limits> 

/* text file example: 
    john 
    3453 
    23 

    james 
    87 
    1 

    mike 
    9876 
    34 
*/ 


struct entry 
{ 
    // Passengers data 
    std::string name; 
    int weight; // kg 
    std::string group_code; 
}; 

entry read_passenger(std::ifstream &stream_in) 
{ 
    entry passenger; 
    if (stream_in) 
    { 
     std::getline(stream_in, passenger.name); 
     stream_in >> passenger.weight; 
     std::getline(stream_in, passenger.group_code); 
     stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 

    return passenger; 
} 

int main(void) 
{ 
    std::ifstream stream_in("data.txt"); 
    std::vector<entry> v; // Contains the passengers data 
    const int limit_total_weight = 10000; // kg 
    int total_weight = 0;     // kg 
    entry current; 
    if (stream_in) 
    { 
     std::cout << "open file" << std::endl; 
     while (!stream_in.eof()) // Loop has no end 
     { 
      std::cout << current.name << std::endl; // Nothing will be displayed 
     } 
      return 0; 
    } 
    else 
    { 
     std::cout << "cannot open file" << std::endl; 
    } 
} 
+1

在你的主程序中你將什麼地方分配給'current.name'?你在哪裏讀取'stream_in '? – Mat

+0

你錯過了讀乘客的詳細信息 –

回答

4

看來你忘了曾經打電話read_passenger,所以你的循環不斷連連打印的current.name默認(空)值。 (你應該得到很多很多的換行符,雖然它並不是「完全不顯示任何東西」)。

+2

因爲它需要發佈的代碼的好一半,所以很遺憾:) –

+0

感謝您的回答!您無法看到樹的木材^^ – burner007

相關問題