Skip to content

C++ string to int conversion – Including Test Cases

C++ string to int conversion with program example and multiple test cases to handle error checking string inputs with examples. Conversion example includes program with and without atoi function.

C++ string to int conversion using atoi() function

atoi() is the stdlib header file library function. If you are using “using namespace std;” then no need to include the header file to get this function, however, if you still see compiler error, then consider including  stdlib header file i.e. #include <stdlib.h>.

C++ string to in code


#include <stdlib.h>
#include<iostream>
using namespace std;

int main()
{
std::string str = "2018";

//Note: You have to use c_str() function of str

int x = std::atoi( str.c_str() );

cout<<"Int value ="<<x<<endl;

return 0;

}

Output:
Test Case-1
input: str = “2018”.
Output: Int value =2018

Test Case-2
input: str = “-2018”.
Output: Int value =-2018

Other test cases:
In inputs are like str = “”; or “y2018”;, the the value will be 0
If the string contains value like “2018y” or “2018yz2019”, then 2018 will be extracted.

So, it is better to check if the string contains only digits for string to integer conversion in C++ program to avoid exception or error. Example given below.

In this program we have written a custom function “isNumericString” that validated that every char of string is an integer except -ve sign. Because we want to get both -ve and +ve integer value. We have used C++ isDigit() function to check if char is an integer in the custom function.

C++ String to int code with error checking and string validation


#include <cctype> // or ctype.h isDigit function
#include <stdlib.h>
#include<iostream>
using namespace std;


/*Check if all character of strings are digits except
* - ive sign. We are allowing negative sign as we
*want to handle +ive and -ve int values in string to int
* conversion.
-*/

bool isNumericString(string str){

      if(str.length() == 0){
            return false;
      }           

      for (int i = 0; i < str.length(); i++){

            if (isdigit(str[i]) == false && str[i] != '-'){
                  return false;
            }
      }

      return true;
}


int main(){

      std::string str = "2018";

      //Note: You have to use c_str() function of str

      if(isNumericString(str)){

            int x = std::atoi( str.c_str() );

            cout<<"Int value ="<<x<<endl;

      }else{

            cout<<"Invalid input: the string should contain onny numbers"<<endl;

      }

      return 0;

}

As an output, this C++ string to int program gives only positive or negative integer value or else it warns user for invalid input.

C++ string to int without atoi() library function

This C++ program example will convert string to integer number without using atoi() function. We have written a custom function stringToInt(string str) that will do the conversion using stringstream class in C++.

Then technique to convert string to integer number is very simple. just read the input string into a stringstream object and write back to int.

CPP Code



#include <sstream>
#include <iostream>
using namespace std;

//Function to convert string to int
int stringToInt(string str){     

      int num;
      std::stringstream strToInt;

      // read the string
      strToInt << str;

      //write to integer number
      strToInt>> num; 

      return num;

}
//Test code for string to int conversion
int main(){

      string str = "123";

      int number = stringToInt(str);
      cout<<number <<endl;

      return 0;
}

Published inC++ Programming Examples