Hi all,
I need a help from you.

I'm writing a c++ console program that only accept only positive number.
If the user enter an invalid number like negative and string, I want to display like

cout << "Enter a number";

I want to loop this message until user enter valid input.
I'm using an integer variable for cin.
So if the user enter string input, the program occurs error.
I don't know how to loop for that condition bcoz I assumed that user may also enter string as invalid input.
So if the user enter negative number or string, I want to display again and again this message.

Thanks in advance,
with regards

Recommended Answers

All 4 Replies

hai friend
i think you can get some idea by seeing this..
Just enter either the number or the string an store in it a char array
And later u may use isnum() to check whether it is a number or a character...

See if something like this http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/ will help you at all. You can use the fact that it doesn't convert if there is no valid number there to your advantage (and just account for the negative values post hoc)

Scan String thn use a function like

int isNum(char c)
    if ( c < '0' || c > '9' ) return -1; 
    return c - '0';

Function works for single char .. you may try for string ..
or else u can use same function for every char of the string and check return value for them all..

This may help u more

// Returns 1 if number or o if its strings
int isNumber(char num[])
	int i = 0;
	int flag = 1;
		flag = 0;
   return flag;
Be a part of the DaniWeb community

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