在c++中读取文本文件和显示数据

Read text file and display data in C++

本文关键字:显示 数据 文件 取文本 c++ 读取      更新时间:2023-10-16

我想读取一个文本文件并显示数据。问题是while循环没有结束,也不显示任何内容。怎么了?

#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;
    }
}

似乎你忘记了调用read_passenger,所以你的循环一次又一次地打印current.name的默认(空)值。(不过,您应该得到很多很多的换行符,这并不完全是"不显示任何东西")。