Convert String to Int in C++

Learn via video courses
Topics Covered

Overview

Strings are an array of characters. We can convert a string to int C++ using stoi(), atoi(), stringstream, sscanf(), for Loop, or strtol(). The header file for stoi() is , for atoi(), sscanf(), strtol() and stringstream is .

Prerequisites

To convert string to int C++, let's understand some Data Types in C++. In C++, data is stored using a variety of data types. The type of data used to hold a value impacts how it can be modified.

String operations, for example, can be used to manipulate the contents of strings but not with numerical numbers.

These are some of the data types in C++:

Data typeValue StoredExample
intInteger1, 2, 3, 10, 100
charCharacters'a', 'b', '#'
boolTrue/Falsetrue or false, 0 or 1
floatDecimal1.03, 3.140, 8.1145
arrayContinous group of same data type{1, 2, 8, 100}
stringContinous group of characters"abcd"

Methods to Convert String to Int in C++

Suppose you are reading a file that contains a list of numbers. When you read this file, you get these numbers in text format, but it's difficult to do numerical processing on the string, right? That's why C++ provides us with functions to convert a string to an integer.

Using stoi() function

To convert string to int c++, stoi() can be used, a function that extracts integers from a string.

Syntax:

Parameters: The stoi() function accepts a string as an argument.

Return value : The stoi() function returns an integer value.

Header file: <string>

The stoi() function accepts a string as an argument and converts the string's integer component to an integer type. It will only consider integer values until the first non-integer character or the end of the string.

Let's understand string to int c++ with sample code:

Code

Output:

Explanation:

  • In the first string str1 = "42", stoi(str1) converts all the integer values of str1 to int and stores them in num1.
  • In the second string str2 = "54 fifty four"; stoi(str2) converts all the integer values of str2 till the first non-integer value that is space " " to int and stores them in num2.
  • In the third-string str3 = "62 sixty-two 54"; stoi(str3) converts all the integer values of str1 till the first non-integer value that is space " " to int and stores them in num3.

But let's take a case when the first value is a non-integer value.

Output:

Explanation: This will give a runtime error. This is because when stoi() hits a non-integer value or a white space, it terminates while traversing. If the starting character is a non-integer value, the stoi() function terminates, giving an error as shown in the output.

Using atoi() function

To convert a string to int in C++, atoi() can also be used, atoi() method works similarly to the stoi() function; it also converts a string to an integer. But the difference is that only C-style strings such as character array and string literals are supported by atoi(), whereas stoi() supports both C and C++ style strings.

Syntax:

Parameters: The atoi() function accepts a pointer to a character array as an argument.

Return value : The atoi() function returns an integer value.

Header file:

Let's understand with sample code:

Code

Output:

Explanation:

  • In the first string str1 = "42", stoi(str1) converts all the integer values of str1 to int and stores them in num1.
  • In the second string str2 = "54 fifty four"; stoi(str2) converts all the integer values of str2 till the first non-integer value that is space " " to int and stores them in num2.
  • In the third-string str3 = "62 sixty-two 54"; stoi(str3) converts all the integer values of str1 till the first non-integer value that is space " " to int and stores them in num3.

But let's take a case when the first value is a non-integer value.

Output:

Explanation: If the starting character is a non-integer character, the atoi() function returns "0". It doesn't give any error message like stoi() on the output screen.

Using stringstream

To convert string to int C++, stringstream can also be used. A stringstream class is a stream class that allows you to read from a string by associating a string object with a stream (such as cin). A numeric string is converted to an int type using the stringstream class.

Syntax:

Parameters : The stringstream object accepts a string as an argument:

Header files : and

Let's understand with sample code:

Code

Output

Explanation: stringstream strm(str); is declaring a stringstream object on string str. strm >> num; takes input from string stream and writes them to num.

But let's take a case when the first value is a non-integer value.

Output:

Explanation: If the starting character is a non-integer character, the stringstream also returns "0" like atoi(). It doesn't give any error message like stoi() on the output screen. Use this C++ Compiler to compile your code.

Using sscanf() function

The sscanf() function is used to convert a string to an integer in C++. It works by parsing the input string based on a specified format and extracts the integer value. It is a versatile function that allows for more complex string-to-integer conversions with proper error handling.

Syntax:

Parameters: str is a pointer to the input string that needs to be converted to an integer. format is a format string that defines how the conversion should be performed. ... is additional arguments that correspond to the conversion format specifiers in the format string.

Return value: If successful, sscanf() returns the number of input items successfully matched and assigned, which should be 1 in the case of a single integer conversion. If the conversion fails, sscanf() returns a value less than the number of input items. It can be used to handle errors.

Header file:

Let's understand with sample code:

Code

Output:

Explanation: In this example, the sscanf() function is used to convert the string "42" to an integer. The format specifier "%d" specifies that the input should be interpreted as an integer. The result variable is used to check if the conversion was successful, and if so, the converted integer value is stored in the num variable. If the conversion fails, the program handles the error and prints "Conversion failed."

Using for Loop

Converting a string to an integer using a for loop involves iterating through each character of the string, checking if it's a digit, and building the integer value. This method is a manual way to convert a string to an integer and allows for custom error handling.

Syntax:

Parameters: str is the input string that needs to be converted to an integer.

Return value : The integer value extracted from the string, or an error handling mechanism if needed.

Header file:

Let's understand with sample code:

Code

Output:

Explanation: In this example, a for loop is used to iterate through each character of the input string "42". For each character, it checks if it's a digit (0-9) by comparing it to the ASCII values of digits. If the character is a digit, it updates the num variable by multiplying the current value by 10 (to shift digits left) and adding the numeric value of the character (by subtracting '0'). This way, the for loop builds the integer value from the string. You can also add error-handling logic for cases where non-numeric characters are encountered in the string.

Using strtol() function

The strtol() function is used to convert a string to a long integer in C++. It allows for more flexibility and error handling than simple conversion functions like atoi(). This function can be used when you need to handle errors and perform base conversions (e.g., hexadecimal or octal).

Syntax:

Parameters: str is a pointer to the input string that needs to be converted to a long integer. endptr is a pointer to a pointer to char, which is used for error checking. After the call to strtol(), it points to the first character that was not used in the conversion. base is an integer that specifies the base for the conversion (e.g., 10 for decimal, 16 for hexadecimal).

Return value : If successful, strtol() returns the converted long integer value. If the conversion fails, it returns 0 and sets errno to ERANGE for overflow or EINVAL for invalid input. You should use endptr to check for errors.

Header file:

Let's understand with sample code:

Code

Output:

Explanation: In this example, the strtol() function is used to convert the string "42" to a long integer. The base is specified as 10 for decimal. The endptr is used to check for conversion errors. If str is equal to endptr, it means the conversion failed, and an error message is printed. Otherwise, the converted long integer value is printed.

Difference between stoi() and atoi()

stoi()atoi
Both C++ and C-style strings, such as character array and string literal, are supported by atoi().Only C-style strings such as character array and string literal are supported by atoi().
Header file to be imported is Header file to be imported is
If the starting character is a non-integer character, the stoi() function gives runtime errorIf the starting character is a non-integer character, the atoi() function returns 0. It doesn't give any errors.

Ready to conquer the world of C++? Enroll in our Free C++ course and become a certified C++ maestro! Begin your journey now.

Conclusion

  • The string to int C++ can be converted using stoi, atoi, stringstream methods.
  • To convert string to int C++, some header files have to be imported. Header files to be imported to convert string to int c++ using stoi() is <string>, for atoi() is <cstdlib>, and for stringstream <string> and <sstream>.
  • If the starting character is a non-integer character, the stoi() function gives runtime error, whereas atoi() and stringstream return 0, which doesn't give any error.