我想读取文本文件并显示数据。问题是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;
}
}
在你的主程序中你将什么地方分配给'current.name'?你在哪里读取'stream_in '? – Mat
你错过了读乘客的详细信息 –