How to use For Loop Convert Strings into int In C++
It is the naive method of string-to-int conversion where we compare each character to its ASCII values and then get the value of that numeric character.
Below is the C++ program used for loop to convert strings into numbers:
C++
// C++ Program to convert String // into number using for loop #include <bits/stdc++.h> using namespace std; int main() { string number = "13" ; int i = 0; // Traversing string for ( char c : number) { // Checking if the element is number if (c >= '0' && c <= '9' ) { i = i * 10 + (c - '0' ); } // Otherwise print bad output else { cout << "Bad Input" ; return 1; } } cout << i; } |
13
However, the above functions can not be used to convert the string with negative numbers to an integer. For this, we have to check that the string’s first index contains the “-” symbol if yes then we will convert the number to an integer and then use this “-” sign in front of this to symbolize that the number present in the string is a negative number.
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings.
Example:
str=”191″
num=191
There are 5 significant methods to convert strings to numbers in C++ as follows:
- Using stoi() function
- Using atoi() function
- Using stringstream
- Using sscanf() function
- Using for Loop
- Using strtol() function