Related Articles

# C++ Program to Convert String to Integer

• Last Updated : 01 May, 2020

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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

 `// C++ program to convert String into Integer``#include ``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;``}`
Output:
```12345
```

How to do using library functions?

Please refer Converting Strings to Numbers in C/C++ for library methods.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up