how to identify if a string is a number and if it is, convert it to an int? (C++)
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c">How to parse a string to an int in C++?</a>  </p>
</blockquote>



<p>I have a simple program thats input regularly is numbers (guessing game pretty much), however I need to add an option where if the user types "help" or "/h" or "?" the program will display a help menu...</p>

<p>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...</p>

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

<p>thanks!</p>

<p>EDIT: According to what I read around from your answers most of you say <code>stringstream</code> is the best way to go... I made a small piece of code to try to understand how <code>stringstream</code> works but I am getting a few errors... any idea why?</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;

using namespace std;

int str2int (const string &amp;str) {
  std::stringstream ss(str);
  int num;
  if((ss &gt;&gt; num).fail())
  { 
      num = 0;
      return num;
  }
  return num;
}

int main(){
    int test;
    int t = 0;
    std::string input;
    while (t !=1){
        std::cout &lt;&lt; "input: ";
        std::cin &gt;&gt; input;
        test = str2int(input);
        if(test == 0){
            std::cout &lt;&lt; "Not a number...";
        }else
            std::cout &lt;&lt; test &lt;&lt; "\n";
        std::cin &gt;&gt; t;
    }
    return 0;
}
</code></pre>

<p>Errors:</p>

<pre><code>Error C2079:'ss' uses undefined class std::basic_stringstream&lt;_elem,_traits,_alloc&gt;'
Error C2228: left of '.fail' must have class/struct/union
Error C2440: 'initializing': cannot convert 'const std::string' into 'int'
</code></pre>
