user873286
user873286

Reputation: 8079

C++ file input problem

Hi Guys! I have the following code:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MAXN 301

string names[MAXN];
vector<string> names_vec;

int main(int argc, char **argv)
{
    ifstream fin(argv[1]);
    int n;
    fin>>n;
    string line;
    while(getline(fin, line))
        names_vec.push_back(line);
    for(int i=0; i<names_vec.size(); i++)
        cout<<names_vec[i]<<endl;
    return 0;
}

and names.in file for input:

5
CLEOpatra
AISHWARYA rai
jOHn f. KeNNeDy
leonardo DA Vinci
tyleR durdeN

When i compile it and run it first prints empty line, that names_vec[0] is empty line. Can anyone explain why and how can I fix it?

Upvotes: 1

Views: 291

Answers (1)

Dawson
Dawson

Reputation: 2771

The problem is that you're mixing the >> operator with calls to getline. Generally, you want to use one or the other, but not both of them together.

The reason you get an empty string in your vector is because >> will NOT consume the whitespace which causes it to stop. That is, it reads the "5", finds the newline character after it, and then stops, leaving the newline character in the ifstream.

Then, the call to getline encounters the newline character and immediately says, "Done! I read a line!". It consumes the newline character and returns the entire string leading up to it -- which in this case was the empty string.

If you know that your data will be formatted properly (no invalid input), it might be easiest just to use >> to read the entire file. Otherwise, I would recommend using getline to read each line one at a time, then using a stringstream object to parse the data out of the line.

EDIT

I just noticed that the rest of your input has first/last names separated by spaces. Since >> stops on spaces, it would probably be easiest to use getline to read the entire file. Example of reading the 5:

string line;
getline(fin, line);

stringstream converter;
converter << line;

int n;
converter >> n;

Upvotes: 6

Related Questions