📅  最后修改于: 2023-12-03 14:59:47.325000             🧑  作者: Mango
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 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:
result
to 0.result
.result
.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.
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.