Search code examples
c++fstreamgetline

reading strings and numbers from input file stream using getline


I get the syntax for getline(ifstream foo, string bar) function and I know its third parameter which is delimiter, is set to '\n'.

I have a file to read, and it has numbers on first and second column. The problem is that on the third column, I have to read names of countries which may have contain spaces.

I've checked my code is successfully reading numbers from first two columns for sure, but as my code tries to read the country name , I get a 'Segmentation fault (cord dumped)' error message.

My code looks like this:

string name[50];
double year1[50],year2[50];
fstream ifstr;
ifstr.open("thefile.csv");
for (int i=0; (!(ifstr.eof())) || i < 51; i++) {
ifstr >> year1[i] >> year2[i];
getline(ifstr, name[i]);} // expecting this line to be reading/storing
//anything that comes after 3rd column into string array

The given variable for my assignment is way too long and complicated, so I kind of wrote that up to help readability, but that one line is pretty much the problem.

From the instruction sheet, my professor mentioned

Reading the populations is straightforward, and can be done using the standard file IO functions we covered in class (i.e., ">>" using an input stream). However, since the names of some countries contain spaces, we need to use getline instead of >> for the name field. Fortunately, the country is the final field so we can use ">>" to read the populations and then a getline to finish the line. You will need to input data until the end of file is reached. Recall that getline's return value is false if at end of file, so its easy to check for this.

I looked up all sources available regarding this topic, but I couldn't find one that solves this so far.

Please advise.


Solution

  • Your loop condition is wrong. You should only loop while both of those values are true. If either one of them becomes false, you should stop. So the || should actually be &&.

    You also have an out-of-range problem. The condition i < 51 is wrong. A value of 50 for i will overflow your arrays when you index them. So the correct condition is i < 50.

    Finally, eof is not the only condition on a stream that should cause you to stop reading. Just use the bool operator of the stream.

    for( int i = 0; ifstr && i < 50; i++ )