简体   繁体   中英

File first line is not read in c++

  in.open(filename.c_str(), ifstream::in);
  string name, email, group;
  while (in >> name >> email >> group) {
    in >> name >> email >> group;
    cout << name << email << group);
    ...
  }
  in.close();

Consider this code where in is of type ifstream and filename is the name of the file from which we read the data. Format of input file is perfectly fine - many lines with 3 string in each. This piece should simply print all of the data in the file but what id does is printing all of the lines except for the first line. Why is the first line skipped?

Drop in >> name >> email >> group; from the body of the loop. The one in the condition is enough.

You're reading too much.

while (in >> name >> email >> group)

Already reads the data once, the next line reads it again, overwriting your data. Get rid of the repetition and your cout should work just fine.

in.open(filename.c_str(), ifstream::in);
string name, email, group;
while (in >> name >> email >> group) {    //Reads the data into the variables
    cout << name << email << group;        //Outputs the variables.
    ...
}
in.close();

Consider this line:

while (in >> name >> email >> group) {

each time the program hits this line, it executes the code inside the brackets. In this case, 'in' is read and populates name, email, group even before actually entering the body of the loop.

Thus, when the body of the loop is executed, the first line has already been read.

If you strings are not seperated by new line operator in the input file use code the blow to read it.

  ifstream in;
  in.open("urfile.txt",ios::beg);
  string name, email, group;
  while (in.good()) {
    in >> name >> email >> group;
    cout << name << email << group;
  }
  in.close();

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