Question about why cin >> works but not getline

Puzzling section:

1
2
3
4
5
6
7
8
9
10
11
12
 while( 1 )
    {
        //cin.ignore();
        //getline( cin, tabData, '\n' );
        cin >> tabData;
        if( tabData == "0" ){ break; }
        else
        {
            vecData.push_back( tabData );
            cout << "\nNext line: ";
        }
    }


getline refuses to break the loop when I enter "0". cin works fine. I don't understand why.

Complete code below.

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

using namespace std;

void showVecData( vector<string> vecData )
{
    cout << "\nTabulated lines: \n";
    for( vector<string>::iterator itr = vecData.begin(), end = vecData.end(); itr != end; itr++ )
    {
        cout << '\n' << '\t' << *itr;
    }
}

int main()
{
    string tabData;
    vector<string> vecData;
    cout << "\nEnter as many lines as you like. Enter 0 to finish.\n" << endl;
    cout << "\nFirst line of data: ";
    while( 1 )
    {
        cin.ignore();
        getline( cin, tabData, '\n' );
        //cin >> tabData;
        if( tabData == "0" ){ break; }
        else
        {
            vecData.push_back( tabData );
            cout << "\nNext line: ";
        }
    }
    showVecData( vecData );
    return 0;
}
Last edited on
Your cin.ignore() looks like it would ignore the first character of your getline() every time through the loop. What is its purpose?
After removing it, the break works. Thanks
Last edited on
Topic archived. No new replies allowed.