Sergey
Sergey

Reputation: 11908

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?

Upvotes: 0

Views: 2857

Answers (4)

Amir Qayyum Khan
Amir Qayyum Khan

Reputation: 473

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

Upvotes: 0

64bit_twitchyliquid
64bit_twitchyliquid

Reputation: 924

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.

Upvotes: 0

ATaylor
ATaylor

Reputation: 2598

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

Upvotes: 0

cnicutar
cnicutar

Reputation: 182639

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

Upvotes: 2

Related Questions