I am creating a simple CLI calculator tool as an exercise. I need to make sure n1 and n2 are numeric in order for the functions to work; consequently, I would like to make the program quit upon coming across a predetermined non-numeric value.

Can anyone give me some direction?

Additionally, if anyone can offer any general tips as to how I could have done this better, I would appreciate it. I'm just learning c++.

Is there a reason you're new'ing your variables isntead of just making them on the stack? Your code isn't safe anymore; it succumbs to exceptions, and is much harder to read.
–
GManNickGFeb 6 '10 at 1:51

4 Answers
4

No need for Boost or writing your own template or forcing yourself to use exceptions vs error codes. cin alone does everything you're asking for.

You can test if ( cin ) or if ( ! cin ) to determine success or failure. One failure (eg, a letter in numeric input) will stop cin from accepting any more input. Then call cin.clear() to clear the error and resume getting input, starting with whatever text caused the error. Also, you can request that a stream throw exceptions on conversion errors: cin.exceptions( ios::failbit ).

What you want to do is read a line of input, or a string, then attempt to convert that line to your numeric form. Boost wraps this in lexical_cast, but you don't need that at all. I've answered a question similar to yours twice, here and here. Read those posts to understand what's going on.

This is good for making Boost's lexical_cast no-throw, but if you're implementing it yourself, there's no reason to waste time throwing and catching an exception. Implement them in terms of each other, where the throwing version uses the no-throw version:

There is more trouble in your code: you're newing everything! Is there a reason for that? Consider if any part of your code throws an exception: now you jump out of main and leak everything. If you stack allocate your variables, they will be guaranteed to destruct.

It's hard to be one-size-fits-all. For a calculator program, you want to accept input like 1+1. cin >> temp_string makes that difficult. Shouldn't input like 123nan be rejected once the letters are encountered, not greedily early?
–
PotatoswatterFeb 8 '10 at 21:25

Another interesting approach could be to construct a parser with Boost.Spirit library, though it is an advanced technique heavily exploiting C++ metaprogramming features. If you'd like to try it, check the quick start examples

Probably a lot of C++ guys will hate me for this, but even while C++ has all these new shiny strings and I try to stay with C++ strings as long as possible to feel clean, in this case the simplest and considerably also cleanest thing is to stick with good ol' C: