A problem with using getline

closed account (oLC9216C)
I am going to run the program until the user say stop, part of my program is using getline, but after the first time, it doesn't work any more.

1
2
3
4
5
6
7
do
{
   cout << "Enter a sentence.\n";
   getline(cin,line);
   cout << "Do you want to enter the sentence again?\n;
   cin >> ans;
}while(ans == 'y'); 


The output is like
Enter a sentence.
Hi.
Do you want to enter the sentence again?
yes
Enter a sentence.
es
Do you want to enter the sentence again?
1
2
3
4
5
6
7
8
9
10
11
    string line;
    char ans;

    do
    {
       cout << "Enter a sentence.\n";
       getline(cin,line);
       cout << "Do you want to enter the sentence again?\n";
       cin >> ans;
       cin.ignore();    // remove '\n' newline from buffer
    } while(ans == 'y');
In your code, you are treating ans like a char while(ans == 'y'), but you are inputting it as a string.
Do you want to enter the sentence again?
yes  <--- this should be a single 'y'


I propose that you change ans to std::string and do:
1
2
3
4
5
6
do {
    // ...
    cout << "Do you want to enter the sentence again?\n";
    getline(cin, ans);
}
while (ans == "yes");


Also you might be interested to read this:
http://www.parashift.com/c++-faq/istreams-remember-bad-state.html
Catfish4 wrote:
In your code, you are treating ans like a char while(ans == 'y'), but you are inputting it as a string.

I don't see that anywhere? This code cin >> can input a string, char, number or any type for which the >> operator has been overloaded.
@ Chervil: you quoted it yourself: while(ans == 'y').
Sorry, you lost me there.

That statement is comparing a char variable with a char literal. Where is the string previously mentioned "but you are inputting it as a string."?
@ Chervil: the "yes" in the OP's test run looks like a string. So what I meant was, the OP tries to input a string into a char.
Thanks. I'd studied the code in detail but not studied the test data so closely.
In this case I'd suggest instead of a simple cin.ignore();, something like cin.ignore(1000, '\n' );, or the more general:
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

This is a very common problem, I think maybe there should be a sticky thread for it, that could simply be referred to, rather than the same question and answer over and over again.


Last edited on
Topic archived. No new replies allowed.