Output problem

I've just written the following code. Everything the program gives output is as expected..but a '1' is automatically printed. Thats unexpected.

Here you'll find the output look - http://pho.to/6lxpd

Whats wrong here?

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
#include <iostream>

#include <string>

using namespace std;

int main()

{
    int n;

    string line;

    cin>>n;

    for(int i=0; i<=n; i++)
    {
        getline(cin, line);

        int cnt=1;

        int sz = line.size();

        for(int j=0; j<sz; j++)
        {
            if(line[j]==' ')
                cnt++;

        }

        cout<<cnt<<endl;

    }

    return 0;
}
Common problem when you mix >> with getline:



line 14: User is prompted for input. You input "2" and press enter, which puts 2\n in cin's input buffer. The >> operator then extracts the number 2, which leaves \n in cin's input buffer.

line 18: Since the input buffer is not empty, the user is NOT prompted for input. Instead, getline extracts the \n from the input buffer. Making 'line' an empty string, and clearing the input buffer. The input buffer is now empty.

line 20: cnt=1

line 24: this loop is skipped because sz==0 (line is an empty string)

line 31: cnt is printed (printing your mysterious '1')



The solution is to clear the input buffer between line 14 and line 18. You can do this by calling getline an extra time, or by calling cin.ignore and ignore all character up to the next whitespace.
Thanks a lot! It is supper clear now. You are awesome Disch! :)
Registered users can post here. Sign in or register to post.