C++ Program to Convert String to Integer
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
// C++ program to convert String into Integer #include <bits/stdc++.h> using namespace std; // function for converting string to integer int stringTointeger(string str) { int temp = 0; for (int i = 0; i < str.length(); i++) { // Since ASCII value of character from '0' // to '9' are contiguous. So if we subtract // '0' from ASCII value of a digit, we get // the integer value of the digit. temp = temp * 10 + (str[i] - '0'); } return temp; } // Driver code int main() { string str = "12345"; int num = stringTointeger(str); cout << num; return 0; } |
chevron_right
filter_none
Output:
12345
How to do using library functions?
Please refer Converting Strings to Numbers in C/C++ for library methods.
Recommended Posts:
- Convert string to char array in C++
- How to convert a single character to string in C++?
- Program to convert IP address to hexadecimal
- Convert a floating point number to string in C
- Program to convert the diagonal elements of the matrix to 0
- How to convert C style strings to std::string and vice versa?
- C++ program to Convert a Matrix to Sparse Matrix
- C++ Program to compare two string using pointers
- Program to reverse words in a given string in C++
- Program to extract words from a given String
- Program to Parse a comma separated string in C++
- Program to replace every space in a string with hyphen
- C++ Program to count Vowels in a string using Pointer
- Program to reverse a string (Iterative and Recursive)
- Program to find the kth character after decrypting a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

