2011-08-30 95 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

相关问题