In the following very simple program, if the input is not an integer (e.g. a character symbol), then the output screen would flash and go away. Is there a way to have the output "bad" when one enters a non-integer, just as when one enters a negative number?
Thanks in advance!

int main()
{
    int x;
    cout << "enter integer: ";
    cin >> x;
    if (x>0) 
       cout << "good";
    else
       cout << "bad";
    return 0;
}

So, your wondering if you can input characters that are not integers? Sure you can. You can use char, getline, or string. I would suggest char if you are just starting to learn.

To allow the user to enter in more than one letter simply add an array to the char statement, as such:
char word[20];

This allows the user to enter and store 20 letters. Hope this was what you were asking for.

Hi, no, I don't mean how to input characters (I know you can do that if you declare x to be char type). What I'd like to know is, if I declared the variable x to be int type, and when running the program, if you entered a character/symbol (say "*", or "X"), then I want the screen to display the word "bad", rather than just flash away. In other words, I'd like there to be an output even when the input is an invalid type.


So, your wondering if you can input characters that are not integers? Sure you can. You can use char, getline, or string. I would suggest char if you are just starting to learn.

To allow the user to enter in more than one letter simply add an array to the char statement, as such:
char word[20];

This allows the user to enter and store 20 letters. Hope this was what you were asking for.

My usual advice is to always read all user input as a string. If you want a numeric value, attempt to perform a conversion. If the conversion fails, issue a message or something; otherwise you successfully obtained a numeric value, so continue.

Could you please show how exactly to do so in this particular program? (How to modify the code?) Thanks in advance.

My usual advice is to always read all user input as a string. If you want a numeric value, attempt to perform a conversion. If the conversion fails, issue a message or something; otherwise you successfully obtained a numeric value, so continue.

Hi, no, I don't mean how to input characters (I know you can do that if you declare x to be char type). What I'd like to know is, if I declared the variable x to be int type, and when running the program, if you entered a character/symbol (say "*", or "X"), then I want the screen to display the word "bad", rather than just flash away. In other words, I'd like there to be an output even when the input is an invalid type.

Oh sorry, I must have read it too fast. >.<

Anyways, I agree with what Dave said. To implement this into the code just add the <string> header, and turn 'int' into 'string'.

Thanks a lot, both. However, it doesn't seem to solve my problem. It seems you answers (including the linked page) deal with only when x is changed to be a string. But what I want is, really, that x is supposed to be an integer, which can be used for computation for example, but on the other hand, when user enters a character, I'd like the program to tell him, for example, "your input must be a number, not character!" (or "bad" in the original code). And if the input was an integer, then the program will be able to continue with whatever it does with that integer (e.g. compare whether x>0, or do arithmetic operations...). If I use your solution and declare x to be a string, then "(x>0)" will not make sense and not even pass compiling.

So is there a way?

(by the way I tried cin.ignore and it didn't work)

If I use your solution and declare x to be a string, then "(x>0)" will not make sense and not even pass compiling.

Well, if you don't get an integer because the user didn't enter a valid one, then "(x>0)" makes no sense either. You can do it your way by recognizing input failure and cleaning up the input stream. I believe there are sticky notes ("Read Me" items) where such things are described. Six of one, a half dozen of the other.

Maybe this will help :

int x = 0;
cin >> x; //get input, expecting an numeric value
if(! cin ) //check if input wasn't a numeric value
{
   cin.clear(); //clear the stream
     while(cin.get() != '\n')  //discard all bad inputs up until the line end
          ;    

   cout<<"Bad\n"; //tell user the input is bad
}
else cout<<"good\n";

It works! Thank you very much firstPerson!

Maybe this will help :

int x = 0;
cin >> x; //get input, expecting an numeric value
if(! cin ) //check if input wasn't a numeric value
{
   cin.clear(); //clear the stream
     while(cin.get() != '\n')  //discard all bad inputs up until the line end
          ;    

   cout<<"Bad\n"; //tell user the input is bad
}
else cout<<"good\n";

Hmmm, it works if one enters a character input, but not if one enters a float type (e.g. "2.4"): in the latter case the screen would again flash away, instead of displaying "Bad".

(by the way, of course I have slightly modified your code, so x is not assigned a value at the beginning but gets a value from input:

int x;
cout << "Enter an integer: ";
cin >> x;
...

It works! Thank you very much firstPerson!

If you need only whole value integers. Then use a typecast on float and use that whole value.

float f = 12.33;
int i = int( f ); //i = 12

Then work with 12

Thanks, this is new to me, too. However, this is still not what I mean to want the program do (sorry for seeming stubborn, maybe there's no way anyway, but just in case...). To put it simply:

What I mean is to have a program which will use an integer x, whose value is entered as input (e.g. "What is your age?"), but when the user accidentally enters any non-integer (such as character "Q", float "8.72"), he will get a message on the screen "Wrong input entered", rather than having the screen just flash and then go dark. The last program suggested by you does solve part of the problem (entering character will result in an error message), but entering a float type ("53.97") will not produce the error message but instead have the screen flash and then go dark.

I wonder if there is a way to be able to deal with invalid input being not only character but also float and any other non-integer type. (If there is, it's probably complicated, seeing the one you suggested).


If you need only whole value integers. Then use a typecast on float and use that whole value.

float f = 12.33;
int i = int( f ); //i = 12

Then work with 12

Thanks, this is new to me, too. However, this is still not what I mean to want the program do (sorry for seeming stubborn, maybe there's no way anyway, but just in case...). To put it simply:

What I mean is to have a program which will use an integer x, whose value is entered as input (e.g. "What is your age?"), but when the user accidentally enters any non-integer (such as character "Q", float "8.72"), he will get a message on the screen "Wrong input entered", rather than having the screen just flash and then go dark. The last program suggested by you does solve part of the problem (entering character will result in an error message), but entering a float type ("53.97") will not produce the error message but instead have the screen flash and then go dark.

I wonder if there is a way to be able to deal with invalid input being not only character but also float and any other non-integer type. (If there is, it's probably complicated, seeing the one you suggested).

Then make another test case for floating point,

float temp = 0;
int val = 0;
cin >> temp;
//check for non number character error

int val = int( temp ) ; //get the whole value

if( val < temp ) cout << "bad\n"; //val should equal temp

So do the error check when temp is not a numeric value, then do
another check to see if the number entered is a float or a integer.
The second test might not always work.

Thanks. I combined your two solutions and modified the program as follows, and it works to my satisfaction so far :icon_smile:. firstPerson, your unfailing help is really appreciated! :icon_lol:
(So what started as a seemingly simple problem turned out to require a not-so-simple code.)

(By the way, what does "if (! cin)" mean exactly? I copied yours but not sure the exact function of it. Can you put the "!" in front of any statment?)

int main()
{     
    float x;   
    int i;
    cout << "How old are you? ";
    cin >> x;               //get input, expecting a numeric value
    cin.ignore(20, '\n');
    if(! cin )              //check if input wasn't a numeric value
    {
         cin.clear(); //clear the stream
         while (cin.get() != '\n');  //discard all bad input up until the line ends   
         cout << "Your age should be a number.\n"; //tell user the input is bad
    }
    else if (int(x)<x)    //check if input was not an integer, e.g. of float type
         cout << "Your age must be a whole number.\n";    
    else 
    {
         cout<<"(Good valid input.)\n";
         i = int(x);          //change x to integer type
         cout << "You are " << i << " years old.\n";
    }
    cin.get();
    return 0;
}

Then make another test case for floating point,

>>(By the way, what does "if (! cin)" mean exactly? I copied yours but not sure the exact function of it. Can you put the "!" in front of any statment?)
<<

First realize that "cin" is a istream object, you might not understand what the means until you get to learn about class. Anyways, istream overloads the ! opertor so you could use it in conjunction with istream object.

So, when you do something like this :

int x = 0;
cin >> x;

Since x is a integer, and you are using cin to get a integer for an input,
then that means that cin is expecting a integer to be inputted. By if an
integer has not been inputted, cin sets off flags. These flags are just
bits. When a bit that handles fail in input is set, then that bit is set to
true and when everything is fine, that bit is false. So that means you
can use cin to check if certain bits has failed or not, and if so then whatever that bit represents( maybe failed input of end of file or
hardware failure), is set to true to indicate that something has gone
wrong. You can skip checking the bits and go straight to checking the istream object, cin using the ! operator. The ! operator when using like
this

if ( ! cin ) { ... }

is read as if cin has failed meaning
that if something went wrong, like the user didn't input the type of value expected or memory failure, then go into the { ... } part.

That was a lot, hope you didn't get bored.

Thanks David Sinkula for hte link (need some time to read the whole thing).

Thanks firstPerson for the explanation, no I'm not bored but glad to know something new. By the way is there a reason why you always assign x=0 before the cin >> x? If x is going to be input, why assign it 0 in the beginning? Perhaps there's something to it?

Yea, to show that initializing variable should become a habit for it
will save bugs from appearing when working on bigger projects.

I see (I vaguely guessed that might be the reason). Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.