c++c++11

C++ convert string to int


Used stoi() method to convert string to int, but it converts to int even when there is alpahabet.

string str1 = "45";
string str2 = "31337 test"; 

int myint1 = stoi(str1); // 45
int myint2 = stoi(str2); // 31337

str2 is converted to int, but I don't want this convertion since it has alphabet. If there any way to catch or prevent this conversion.


Solution

  • You can check the number of characters processed.

    string str2 = "31337 test"; 
    std::size_t num;
    
    int myint2 = stoi(str2, &num); // 31337
    //                      ^^^^
    
    // num (the number of characters processed) would be 5
    if (num != str2.length()) {
        ...
    }