我只想阅读文本文件并将数据存储到矢量中。因此,值权重应该是总和,直到达到极限。前四行将被正确读取但以下内容将无法读取。这是什么错误?
#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;
}
答案 0 :(得分:1)
这两行,
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)
也许有更多错误,但上面就是我立即看到的。
干杯&amp;第h。,
答案 1 :(得分:1)
我试着不要混合格式化和面向行的输入,正是出于这个原因。如果是我,我必须在任何地方使用getline
,我会在任何地方使用getline
:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
#include <sstream>
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();
}
std::istream& operator>>(std::istream& stream_in, entry& passenger)
{
std::getline(stream_in, passenger.name);
std::string weightString;
std::getline(stream_in, weightString);
std::istringstream (weightString) >> passenger.weight;
std::getline(stream_in, passenger.group_code);
return stream_in;
}
void read_blankline(std::istream& stream_in) {
std::string blank;
std::getline(stream_in, blank);
}
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 >> current)
{
total_weight = total_weight + current.weight;
std::cout << current.name << std::endl;
if (total_weight >= limit_total_weight)
{
break;
}
read_blankline(stream_in);
}
return 0;
}