0

hello all,
i am new to c++ and just started learning about 1 week ago.

i wrote a (console) program that does simple math, it asks you to enter couple numbers and will output an average.
i want to know how to write and if statement where it will say "input should be a number" if the input is anythign else: letter, $sign or combination of letter and number.

i have been able to do it like this

cin<<value;
if ( value < 0 ) {
       cout<<"value should be more than 0", cin>>value;
}

but i want to know how to do if if value is a letter or anything other than a number

Edited by mani_singh: n/a

4
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by Dave Sinkula
0

Declare it as a char or a std::string

can u give me an example of how to go about doing this

0

That's is not as easy as it sounds...

You need to
- input the number as a string
- test the string making sure only digits were entered
- if not, output error
- if so, convert the string into your number.

I'd wait on this until you learn just a little more, specifically strings and characters. Give it a week or two and come back to this. It's a good task to understand.

0

That's is not as easy as it sounds...

You need to
- input the number as a string
- test the string making sure only digits were entered
- if not, output error
- if so, convert the string into your number.

I'd wait on this until you learn just a little more, specifically strings and characters. Give it a week or two and come back to this. It's a good task to understand.

sounds very confusing
i guess ill try to wait till i learn that part

0

Just to add to that, a number would be:

-Anything containing [0123456789]
-And if it has a decimal point it must contain ONLY one [.]

It would be simple enough to write the logic for that.


...And if you are considering the user entering spaces as well, you have to look at using getline() and then either flushing the input buffer or using getline for everything thereafter.

Edited by iamthwee: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.