Noob here, I'm going through Bjarne Stroustrup's book Programming, Principles and Practice Using C++. (I'm using other resources too though).
Here's the problem, it's from chapter 4 of the book.
1. Write a program that consists of a while loop that (each time around the
loop) reads in 2 ints, and then prints them. Exit the program when a terminating '|' is entered.
I'm sort of lost on this, I know there are a number of ways to get input, but what would the instructions be to sort out the '|' character?
Right now I've got
1 2 3 4 5 6 7
|
int x ;
int y ;
while (cin>>x>>y)
{
cout << " x is: " << x << "\n y is: " << y ;
}
|
which obviously, any time any character at all is entered, the while loop isn't entered.
How do I compare what is input? It seems like this sorta goes beyond the scope of what I've learned so far but maybe that is the point.
I guess I could declare a string that could be compared (ie "type the word "Enter" after you have entered the 2 Integer Variables") But that doesn't seem
as direct as just having it terminate if "|" is input.
EDIT:
Here's my new program. Also I've read that goto isn't recommended (from another book I was reading). I suppose that using Break; as the statement for the if (Enter=="|") test would have the same effect.
How do I test if x or y are valid inputs though? If one gets a character or anything other than an integer value, the program gets stuck in an infinite loop. Why doesn't it wait until the next input?
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 38 39 40
|
int x = 0 ;
int y = 0 ;
string Enter = "" ;
while(true)
{
start:
cout << "\nPlease enter 2 integers, followed by the word 'Enter': " ;
cin >> x ;
cin >> y ;
cin >> Enter ;
if (Enter == "Enter" || Enter == "enter")
{
cout << "x is: " << x << "\ny is: " << y ;
}
else
if (Enter == "|")
{
goto end ;
}
else
if (Enter != "Enter" && Enter != "enter" )
{
cout << "\nOops, please re-enter your numbers\n" ;
goto start ;
}
}
end:
return 0 ;
|