简体   繁体   中英

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 ). So struct sv haven't last value.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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