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

Member Avatar for iamthwee

Declare it as a char[] or a std::string

Declare it as a char or a std::string

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

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.

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

Good choice. But as I said, come back to it. It's an important part of programming.

Member Avatar for iamthwee

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.

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.