how do I identify if a string is a number and if it is, convert it to an int?

Hi,

I have a simple program thats input regularly is numbers, however I need to add an option where if the user types "help" or "/h" or "?" the program will display a help menu...

So essentially I need to be able to differentiate if the input is a string or a number and if its a number, convert it to an int...

What's the best way to get this done? I know I can use atoi to convert a string to an int, but how do I check if the value is numeric?

thanks!
First question is what kind of numbers am I reading in? Next question do I need to stick to atoi, this c way and not use c++ like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <stringstream>

int main()
{
    std::string strIn;
    std::stringstream strConvert;

    std::cout << "Enter a number: (? -- for help)" << std::endl;
    std::getline(cin, strIn);
    double nInput;


    strConvert << strIn;
    strConvert >> nInput;

    if(!strConvert.good())
   {
          if(strIn == "?")
          {
                 std::cout << "A number can be any Real number." << endl;
          }
          else
          {
                 std::cout << "I didn't understand that input please refer to ?-help for more information." << std::endl;
          }
   }
   else
   {
         std::cout << "The number you entered: " << nInput << std::endl;
   }
   return 0;
} // end of main. 
Last edited on
Topic archived. No new replies allowed.