简体   繁体   English

无法读取所有行的数据

[英]Can't read the data of all lines

My code can't read data of all lines.我的代码无法读取所有行的数据。

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();

My data:我的数据:

Johns 3 6 1999 Male 5 7
Jeam  3 7 1998 Male 8 7
Jes   7 9 1999 Male 5 9

When I debug this code, it can't read last line ( Jes 7 9 1999 Male 5 9 ).当我调试这段代码时,它无法读取最后一行( Jes 7 9 1999 Male 5 9 )。 So struct sv haven't last value.所以 struct sv 没有最后一个值。

The main problem is this line:主要问题是这一行:

while (file >> name >> dy >> mth >> year >> sex >> a >> b) {

when you reach the last line of the file you read all those variables but also you reach the end of the file so the whole expression converts to false and you will not execute code in while for the last line当您到达文件的最后一行时,您会读取所有这些变量,但也会到达文件的末尾,因此整个表达式将转换为 false,并且您将不会在 while 最后一行中执行代码

Try something like this:尝试这样的事情:

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

Try this:尝试这个:

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

Build:建造:

g++ -o test main.cpp

Test input file:测试输入文件:

ABC Male
DEF Female
GHI Unknown
KLM Whoknows

Run:跑:

./test test.txt

Output:输出:

ABC Male
DEF Female
GHI Unknown
KLM Whoknows
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM