📜  c++ string to integer without stoi - C++ Code Example(1)

📅  最后修改于: 2023-12-03 14:59:47.325000             🧑  作者: Mango

C++ String to Integer without stoi

In C++, you can easily convert a string to an integer using the stoi function. However, sometimes you may need to convert a string to an integer without using stoi. In this article, we will explore how to do this.

The Algorithm

The algorithm for converting a string to an integer without stoi is quite simple. We will iterate through each character in the string and convert it to an integer using ASCII codes. We will then multiply the resulting integer by the appropriate power of 10 and add it to our result. Here's the algorithm in detail:

  1. Initialize a variable result to 0.
  2. Iterate through each character in the string.
  3. Convert the character to an integer using the ASCII code. Subtract 48 from the ASCII code of the character to get the integer value.
  4. Multiply the resulting integer by the appropriate power of 10 based on its position in the string. For example, if the integer is in the ones place, multiply it by 10^0 = 1. If it's in the tens place, multiply it by 10^1 = 10. If it's in the hundreds place, multiply it by 10^2 = 100, and so on.
  5. Add the resulting value to result.
  6. Repeat steps 2-5 for each character in the string.
  7. Return result.
The Code

Here's the code for the algorithm described above:

#include <iostream>
#include <string>

int stringToInt(std::string str)
{
    int result = 0;
    int factor = 1;

    for (int i = str.length() - 1; i >= 0; i--)
    {
        result += (str[i] - 48) * factor;
        factor *= 10;
    }

    return result;
}

int main()
{
    std::string str = "12345";
    int intValue = stringToInt(str);

    std::cout << "The string " << str << " converted to an integer is: " << intValue << std::endl;

    return 0;
}

In this code, we first define a function stringToInt that takes a string as an argument and returns an integer. Inside this function, we initialize result to 0 and factor to 1. We then iterate through each character in the string in reverse order (starting from the end of the string) and compute the value of the integer using the algorithm described above. Finally, we return the resulting integer.

In main, we define a sample string str and call stringToInt to convert it to an integer. We then print out the resulting integer to the console.

Conclusion

Converting a string to an integer without using stoi is easy with the algorithm described above. This method can come in handy when stoi is not available or when you want more control over the conversion process.