Need non integer character for breaking out of loop

Below is a simple program for class. I need to find a way to break out of the code if a lowercase "n", or "N" is pressed. Right now if 0 is pressed the code breaks while(X != 0). Would it be while(X != 'n|N')





#include <iostream>
using namespace std;

int HighestNumber(int X, int Y, int Z, int Largest);


void main()
{

int X, Y, Z, Largest=0;

cout << "Enter three integers ==> ";
cin >> X >>Y >> Z;


while(X != 0)
{
cout << HighestNumber(X, Y, Z, Largest);
cout << "Enter three integers ==> ";
cin >> X;

if(X == 0)
break;
else
cin >> Y;
cin >> Z;
}
}

int HighestNumber(int X, int Y, int Z, int Largest)

{
if(X > Y && X > Z)
Largest = X;
if(Y > X && Y > Z)
Largest = Y;
if(Z > Y && Z > X)
Largest = Z;
return Largest;
}
Well then do that! what's the problem? you just said what to do! except of course you need to put while (char(X)!='n' && char(X)!='N') instead of while(X != 'n|N')
(char(X)!='n' && char(X)!='N') <- this will not work. The only way that will exit is if the user enters the ASCII code for 'N' or 'n'. If they input the actual letter 'n' cin goes into a bad state because it can't put a letter in an int variable.

The easiest way to do this is to get a single character from the stream, check it to see if it's 'n', and if it isn't, put it back in the stream with unget() and read the number normally.

Pseudocode:

1
2
3
4
5
6
7
8
9
char ch = cin.get();
if( ch != 'n' && ch != 'N' )
{
  // user did not input 'n'
  cin.unget();  // put whatever they did input back in the stream so we can read it again

  int x;
  cin >> x;  // now read it as an integer.
}
Topic archived. No new replies allowed.