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;
}
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.
#include <iostream>
#include <string>
usingnamespace 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;
}