cout << "Enter the first number: ";
cin >> num1;
while (num1 != 'x')
{
cout << "Enter the second number: ";
cin >> num2;
cout << "" << endl;
compute(num1, num2, sum, diff, prod, quotient);
cout << "Enter the first number: ";
cin >> num1;
if ((num1 = 'x')){
return 0;
}
}
return 0;
}
I don't know if something is janky with my "while," but it's written what I want it to do so I can't see anything wrong.
As for my "if," if I write anything, x or whatever else, it breaks the code. If I get rid of it, and continue writing numbers, it will loop successfully. But if I write x, well...it'll repeat the code in a pi-like manner.
My guess is there's something off with my "if" code (CodeBlocks had me double-parentheses on it for some reason. Can someone explain that so I understand why it wanted me to do that?), but I fail to see how. Probably something basic I overlooked?
Any help is appreciated.
You can't read the character 'x' as an int; it must be read as a char.
This is one way of doing it:
1. read the next non-white-space character char c ; std::cin >> c ;
2. if it is 'x' exit from the loop while( .... && c != 'x' && ... )
3. otherwise put the character back into the input buffer std::cin.putback(c)
4. read the number and continue with the loop std::cin >> first_number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int main()
{
double first_number ;
char c ;
while( std::cout << "enter first number or x to quit: " &&
std::cin >> c && c != 'x' && std::cin.putback(c) && std::cin >> first_number )
{
std::cout << "first number is " << first_number << '\n' ;
}
if( c == 'x' ) std::cout << "quitting because you entered x\n" ;
else std::cout << "quitting because of badly formed input (not a number)\n" ;
}
> My guess is there's something off with my "if" code (CodeBlocks had me double-
> parentheses on it for some reason. Can someone explain that so I understand why it wanted me to do that?),
> but I fail to see how. Probably something basic I overlooked?
Yes; use == for equality comparison; = is assignment.