gpt4 book ai didi

c++ - c++中文本文件读取错误

转载 作者:行者123 更新时间:2023-11-30 04:32:54 25 4
gpt4 key购买 nike

我只想读取一个文本文件并将数据存储到一个 vector 中。因此,值(value)权重应该是总和,直到达到限制。前四行将被正确读取,但以下不会被读取。错误是什么?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>

/*
Data.txt

John
6543
23

Max
342
2

A Team
5645
23
*/

struct entry
{
// passengers data
std::string name;
int weight; // kg
std::string group_code;
};

void reservations()
{
std::ofstream file;
file.clear();
file.open("reservations.txt");
file.close();
}

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

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;
while (!stream_in.eof())
{
current = read_passenger(stream_in);
total_weight = total_weight + current.weight;
std::cout << current.name << std::endl;
if (total_weight >= limit_total_weight)
{
break;
}

}
return 0;
}

最佳答案

这两行,

    std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

应该是相反的顺序:

    stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(stream_in, passenger.group_code);

想想 ignore目的是什么。

另外,不是只检查 EOF,而是检查一般错误。

即,而不是

    while (!stream_in.eof())

    while (stream_in)

也许还有更多的错误,但以上是我立即看到的。

干杯,

关于c++ - c++中文本文件读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com