In C, there are two ways to convert string to int: use the sto i() function, which directly receives the string and returns an integer. Use the isringstream class to parse the string into an input stream and extract the integers. The method chosen depends on the string format: stoi() is more concise if the format is unambiguous and has no non-numeric characters; isstringstream is more flexible if the string may contain non-numeric characters or requires custom conversion.
Method of converting string to int in C
In C, convert string (string) to integer (int) has the following two methods:
1. stoi() function
Using the built-instoi()
function is the simplest and most direct Methods. It takes a string parameter and returns an integer.
#include #include int main() { std::string str = "123"; int number = stoi(str); std::cout << "String: " << str << "\n"; std::cout << "Integer: " << number << "\n"; return 0; }
2. isringstream
Another way is to use theistringstream
class. It parses the string into an input stream, from which integers can be extracted using the
>>
operator.
>>
#include #include int main() { std::string str = "456"; std::istringstream iss(str); int number; iss >> number; std::cout << "String: " << str << "\n"; std::cout << "Integer: " << number << "\n"; return 0; }
Which method to choose?
stoi()
function is the simpler and faster option.istringstream
is more flexible.The above is the detailed content of How to convert string to int in c++. For more information, please follow other related articles on the PHP Chinese website!