Reversing words

This is a google code jam question. The input consist of
1st line:integer tells you how many cases
then the number of lines of text separated by space.

ex:
3
this is a sentence
this one too
and this one too

aim is to display it like this

case #1: sentence a is this
case #2: too one this
case #3: too one this and

Here is my code. A very simple error
it does this
case #1:
case #2: sentence a is this
case #3: too one this


Help will be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

int main(int argc, char * argv[])
{
	ifstream infile(argv[1]);

	string data;
    int number;

    while(infile >> number)
	{
	    int num = 1;
	    while(getline(infile, data, '\n') && (num <= number) )
        {
            cout << "case" << num <<":";
            vector<string> lineInfo;
            string token;
            stringstream ss(data);

            while(getline(ss, token, ' '))
            {
                lineInfo.push_back(token);

            }

            reverse(lineInfo.begin(), lineInfo.end());
            for(auto it = lineInfo.begin(); it != lineInfo.end(); ++it )
            {
                cout << *it << " ";
            }
            num++;
            cout << "\n";
        }
	}
        system("pause");
        return 0;

}
Last edited on
before line 17, do this:

1
2
3
#include <limits>
...
infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


EDIT:
The reason you do this is because the >> operator does not extract space characters from the input stream. So after you use the >> operator to read in number, the '\n' character is not extracted. Then when you try to use getline ( which is supposed to read until it encounters a new line character), getline will stop reading immediately because it has read a line delimiter and thus read an empty string. So your first case will print an empty string
Last edited on
Thanks smac89. Very intuitive. Works fine. Cheers!!
Topic archived. No new replies allowed.