*Below is a an exercise that I am practicing on. Does my code make sense?
1. Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them.
Exit the program when a terminating '|' is entered.
int main()
{
int val1 =0;
int val2 =0;
cout<<"Please enter two positive integers.\n";
cin>>val1>>val2;
while (val1<100 && val2<100) //I conditioned my number range less than 100.
{
cout<<val1<<" "<<val2<<'\n';
val1++;
val2++;
int main()
{
int val1 =0;
int val2 =0;
cout<<"Please enter two positive integers.\n";
cin>>val1>>val2; // you read values only once
// instructions: reads in two ints each time around the loop
// The cin >> to int variable can fail, if stream does not contain integral content
// e.g. | is not anumber. On fail, the stream goes to error state and you can read no more.
while (val1<100 && val2<100) // no need to limit. Instructions: two ints ... big, small, negative
{
cout<<val1<<" "<<val2<<'\n';
val1++; // Not in instructions
val2++; // Not in instructions
if (val1 == '|'|| val2 == '|')
// One of these is true, if user typed a number that happens to be ASCII code for |
{
cout<<"'|' terminates.\n"; // Says so, but does not actually terminate
}
return 0; // this return is inside the loop, so program always exits on first iteration
}
Okay, so "read-in" and the "display" of the values happens within the loop. How how would I structure code to meet this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while ()
{
cin>>val1>>val2;
if (val1 == " " && val2 == " ") //no idea on how to condition this with a integer value.
cout<<"val1<<""<<val2<<'\n';
else if (val1 == int('|'))
cout<<"termination character."
}
Now we return to the "errors are signaled". If the user has written |, then the next cin >> val will think that the input cannot be interpreted as a valid value of int and sets the failbit.
The while needs a condition. The cin >> val1 >> val2 can be used as a condition expression.
There is only a minor flaw: every "invalid character" will abort the loop. Not just the '|'.
However, you should already be able (with above information) to write a program that reads pairs of ints and prints them, until you type a non-integer (non-whitespace) character. Do that.