1

I have the code below. The code is followed by a sample input file. When I go to cout the arrays it does it like this:

Output:

Joe
Browns
93
Samantha
Roberts
45

Why is the string only reading until the white-space and then moving on? I thought string accepts white-space? Thanks.

Code:

    ifstream in_stream;

    in_stream.open("in.dat");
    if(in_stream.fail())
    {
        cout<< "Input file opening failed.  \n";
        exit(1);
    }
    vector <string> a;
    int i = 0;
    string dummy;
    while(in_stream>>dummy)
    {
       a.push_back(dummy);
       cout<<a[i]<<endl;
        i++;
    }
    in_stream.close( );

Sample Input File:

Joe Browns
93
Samantha Roberts
45
Alan
  • 1,166
  • 1
  • 9
  • 22

2 Answers2

1

operator>> interprets any kind of whitespace as a delimiter. Use getline() if you need to read entire lines.

us2012
  • 15,457
  • 2
  • 41
  • 61
  • alright, If I do getline(in_stream, dummy); it returns in a funny format; so that's not quite right yet –  Feb 25 '13 at 22:50
  • 1
    @user22507 If it's too funny for you, it might be a problem with your sense of humor :) . Jokes aside, you really should say what's wrong with it. `getline` doesn't normally do any strange formatting. – us2012 Feb 25 '13 at 22:52
0

Change the while loop so you read the whole line.

while (getline(in_stream, dummy))
{
    a.push_back(dummy);
    cout << a[i] << endl;
    i++;
}
Christian Rapp
  • 1,614
  • 20
  • 34
  • 1
    Using .eof in while loop is NOT Good. http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Feb 25 '13 at 22:47