Home ยป How to identify if a string is a number and if it is, convert it to an int?

How to identify if a string is a number and if it is, convert it to an int?

#include <iostream>
#include <string>

using namespace std;

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

int main(){
    int test;
    int t = 0;
    std::string input;
    while (t !=1){
        std::cout << “input: “;
        std::cin >> input;
        test = str2int(input);
        if(test == 0){
            std::cout << “Not a number…”;
        }else
            std::cout << test << “n”;
        std::cin >> t;
    }
    return 0;
}

Error C2079:’ss’ uses undefined class std::basic_stringstream<_elem,_traits,_alloc>’
Error C2228: left of ‘.fail’ must have class/struct/union
Error C2440: ‘initializing’: cannot convert ‘const std::string’ into ‘int’

long int strtol ( const char * str, char ** endptr, int base );

string input;
cin >> input;
if (input == “help” || input == “/h” or input == “?”)
    help();
else {
    bool convertible = true;
    for(string::size_type i = 0; i < input.size(); ++i) {
        if (!isdigit((int)input[0])) {
            convertible = false;
            break;
        }
    }
    if (convertible) {
        int digit = atoi(input.c_str());
        // do guessing game stuff
    }
    else {
        // handle
    }
}

Add Comment

Click here to post a comment

Your email address will not be published. Required fields are marked *