BleuGamer BleuGamer - 4 months ago 23
C++ Question

Why my while loop causes infinite output

I am attempting to build a small program that includes a while loop:

int main() {
int x = 0;
int y = 0;
while (x != '|' || y != '|') {
cout << "Please enter two numbers: \n";
cin >> x >> y;
cout << "You entered: " << x << " and " << y << "\n\n" << endl;
return 0;

I compiled and ran on both my windows box with visual studio and my linux box, and when the break requirement is filled my terminal/cmd fills up infinitely like an infinite loop. I've searched in quite a few places and couldn't find a clear answer. I have tried making the while infinite and putting the break parameter inside to no avail. I have a feeling it has to do with putting the vertical symbol in an integer, but I have had for loops running well with it. The lesson I'm in asks for it and I have workarounds that are 'okay', but would like to know a clean/standard way of doing this.


The infinite loop is because you never check for input failure. After the line cin >> x >> y add:

if ( !cin )

Bear in mind that x and y are ints, so they can only store numbers. When you write x != '|' you are testing whether the person successfully entered the number matching the ASCII character code of |. If you want to be able to inspect each character the person entered, input into a string instead.