May 21, 2010
String to integer c++
String to integer in c++
Given an integer number in string format, for example “12345”. Write a program or function to convert a string to integer in C without using library.
String to integer algorithm
Loop through the characters of the string representing the integer number. Get the integer value of the current digit by subtracting the ASCII code of ‘0’ from the ASCII code of the current character. Multiply that number by 10 raised to the power of the position of that digit in the string. Keep adding those values until all characters are scanned.
Example code
Here is a C++ code to do that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
//Includes #include <iostream> using namespace std; void main() { //Input number in string format char numStr[] = "12345"; //Integer value of the number string //to be calculated int numInt = 0; //Find string length. You can use a built in function //but we are calculating the length manually. int len = 0; while (numStr[len] != '\\0') len++; //This is needed to calculate powers of 10 int power = 1; //Loop in the string character by character //Get the current digit by subtracting the ASCII code of '0' //from its ASCII code. You need to cast the rest to integer //type. Then multiply the result by 10 raised to a power equal //to the position of the character from right to left starting //the count from 0. For example 2 in the example above has //position 2 for (int i = len-1; i >= 0; i--) { numInt += (int)(numStr[i]-'0') * power; power *= 10; } //Print value cout << "Integer value = " << numInt << endl; } |
If you have comments or questions, please use the comments section below. Thanks for visiting.