I want to read a text file and display the data. The problem is that the while loop has no end and does not display anything. What's wrong?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
/* text f开发者_Go百科ile 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;
}
}
It seems you forgot to ever call read_passenger
, so your loop keeps printing the default (empty) value of current.name
again and again. (You should get lots and lots of newlines, though, which isn't exactly "does not display anything').
精彩评论