while loop isnt looping

So i have some homework due next week. the assignment is to ask user to input name and two numbers. then determine and output the lower number. then if the user inputs "y" the program repeats until any other letter is inputted. THe program works once but doesnt loop.

#include <iostream>
#include <string>
using namespace std;

int main()
{
string mystr;
string after;
int x,y;
cout<<"press 'y' to start the program or 'n' to stop"<<endl;
getline(cin, after);
while(after == "y")
{
cout<<"welcome to this program! What is your name?"<<endl;
getline (cin, mystr);
cout<<"Hello " + mystr +" please enter two numbers now!"<<endl;
cin>>x;
cin>>y;
if (x<y)
cout<<x;
else
cout<<y;
cout<<"y to continue or anything else to quit"<<endl;
getline (cin, after);
}
return 0;
}

The problem is that after statement

cout<<y;

the input buffer contains new line character. So the next statement

getline (cin, after);

reads thet new line character instead of your input. You should remove the new line character from the input buffer before issueing getline.
I got rid of the endl in
"cout<<"y to continue or anything else to quit"<<endl; to
cout<<"y to continue or anything else to quit";
this doesnt work
unless u meant something else
vlad is almost right. It's not the cout << y; that causes the problem, it's the cin >>y.

What happens is that when cin >> y executes, it takes whatever's in standard input and puts it into the variable y. However, it doesn't store or get rid of the newline. Thus, when you use getline, it reads until it finds a \n. Since the next character is a \n, getline returns 0. And 0 is not equal to y.

To fix the problem, either consistently use getline, or add cin.ignore() above the last getline() call. This will ignore one character in the standard input, which will be the newline.
I dont know if you should use this, but I always use return main(); or return 0; in my loops. try one of those?
Most compilers fill in the return 0; for you btw, even though it's in the standard.
simply do this:

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
#include <iostream>
#include <string>
using namespace std;

int main() 
{
string mystr;
string after;
int x,y;
cout<<"press 'y' to start the program or 'n' to stop"<<endl;
getline(cin, after);
cout<<"welcome to this program! What is your name?"<<endl;
getline (cin, mystr);
cout<<"Hello " + mystr +" please enter two numbers now!"<<endl;
loop:
cin>>x;
cin>>y;
if (x<y)
cout<<x;
else 
cout<<y<<endl;
cout<<"y to continue or anything else to quit"<<endl;
cin>>after;
if (after=="y")
{
	cout<<"Enter another two numbers."<<endl;
goto loop;
}
return 0;
}
afaik, better don't use goto

It's not the cout << y; that causes the problem, it's the cin >>y.

i think the same

@chipp
It's not the cout << y; that causes the problem, it's the cin >>y.

i think the same


It was a typo.:) Of course I meant cin >> y but copied another statement.
Topic archived. No new replies allowed.