C++ Program to Convert String to Integer
Last Updated :
21 Jun, 2022
Given a string of digits, the task is to convert the string to an integer. Examples:
Input : str = "12345"
Output : 12345
Input : str = "876538";
Output : 876538
Input : str = "0028";
Output : 28
CPP
#include <bits/stdc++.h>
using namespace std;
int stringTointeger(string str)
{
int temp = 0;
for ( int i = 0; i < str.length(); i++) {
temp = temp * 10 + (str[i] - '0' );
}
return temp;
}
int main()
{
string str = "12345" ;
int num = stringTointeger(str);
cout << num;
return 0;
}
|
Time Complexity: O(|str|)
Auxiliary Space: O(1)
How to do using library functions? Please refer Converting Strings to Numbers in C/C++ for library methods.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...