我的代码无法读取所有行的数据。
void read(string name, student *sv, int n) {
ifstream file (name, ios::in);
string name, sex;
int dy, mth, year, i = 0;
float a, b;
while (file >> name >> dy >> mth >> year >> sex >> a >> b) {
cout << name << dy << mth << year << sex << a << b << endl;
sv[i].name = name;
sv[i].date.day = dy;
sv[i].date.month = mth;
sv[i].date.year = name;
sv[i].sex = sex;
sv[i].math = a;
sv[i].physics = b;
++i;
}
file.close();
我的数据:
Johns 3 6 1999 Male 5 7
Jeam 3 7 1998 Male 8 7
Jes 7 9 1999 Male 5 9
当我调试此代码时,它无法读取最后一行(Jes 7 9 1999 Male 5 9)。因此struct sv没有最后一个值。
答案 0 :(得分:1)
主要问题是此行:
while (file >> name >> dy >> mth >> year >> sex >> a >> b) {
当您到达文件的最后一行时,您将读取所有这些变量,但同时也到达了文件的末尾,因此整个表达式将转换为false,并且您将不会在这段时间内执行代码
尝试这样的事情:
std::string line;
std::getline(file, line);
while (file && !line.empty())
{
std::cout << line << std::endl;
//parse line and do stuff
std::getline(file, line);
}
答案 1 :(得分:0)
尝试一下:
// main.cpp
#include <fstream>
#include <ios>
#include <iostream>
#include <string>
struct student {
std::string name;
std::string sex;
};
void read(std::string fname, student *sv) {
std::ifstream file(fname.c_str(), std::ios_base::in);
std::string name, sex;
int i = 0;
while (file >> name >> sex) {
std::cout << name << " " << sex << std::endl;
sv[i].name = name;
sv[i].sex = sex;
++i;
}
file.close();
std::cout << i << std::endl;
}
int main(int argc, char **argv) {
student sv[10];
std::string fname(argv[1]);
read(fname, sv);
}
内部版本:
g++ -o test main.cpp
测试输入文件:
ABC Male
DEF Female
GHI Unknown
KLM Whoknows
运行:
./test test.txt
输出:
ABC Male
DEF Female
GHI Unknown
KLM Whoknows
4