【问题标题】:Read text file and display data in C++读取文本文件并在 C++ 中显示数据
【发布时间】:2011-11-07 00:36:13
【问题描述】:

我想读取一个文本文件并显示数据。问题是 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;
    }
}

【问题讨论】:

  • 你主要在哪里分配任何东西给current.name?你在哪里读到stream_in
  • 您错过了阅读乘客详细信息。

标签: c++ vector stream eof


【解决方案1】:

您似乎忘记了调用read_passenger,因此您的循环会一次又一次地打印默认(空)值current.name。 (不过,您应该得到很多很多换行符,这并不完全是“不显示任何内容”)。

【讨论】:

  • 相当多的事情要忘记,因为它需要一半的发布代码:)
  • 感谢您的回答!只见树木不见森林^^
猜你喜欢
  • 2014-04-13
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多