I am making a function that takes a number from the user's input and finds the absolute value of it. I want to make it return an error if the user inputs anything other than just a number. How would I go about doing that?
(I know that this is probably an easy question for a lot of you, but I'm taking my first programming class in C++ so I know very little. Any help would be greatly appreciated.)
If you are actually trying to program in idiomatic C++, ignore the (intentionally?) bad advice you are being given. Especially the answers pointing you toward C functions. C++ may be largely backwards-compatible with C, but its soul is a totally different language.
Your question is so foundational as to make for a terrible homework assignment. Especially if you're so adrift that you don't know to avoid conio.h and other tragedies. So I'm just going to write out a solution here:
This lets you use the natural abilities of the iostream classes. They can notice when they couldn't automatically convert what a user entered into the format you wanted, and give you a chance to just throw up your hands with an error -or- try interpreting the unprocessed input a different way.
Have you checked out atoi, or the even better strtol? I recommend starting there.
Treat user input as
std::string
orchar *
, then validate whether it contains a valid digit character.Pass your number as a reference and return an error code. Using the function argument as an output parameter.
In addition to the great answers here, you could try using std::stringstream:
http://cplusplus.com/reference/iostream/stringstream/stringstream/
It works like any other stream for the most part, so you could do something like:
HTH!
P.S. personally, I would just use boost::lexical_cast<>, but for a homework assignment you probably won't have boost available to you. If you become a professional C++ programmer, Boost will become one of your best friends outside of the STL.