How to convert string to int in c++

下次还敢
Release: 2024-05-01 13:27:16
Original
783 people have browsed it

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.

How to convert string to int in c++

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; }
Copy after login

2. isringstream

Another way is to use theistringstreamclass. 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; }
Copy after login

Which method to choose?

  • If the string is well-formed and does not contain any non-numeric characters, thestoi()function is the simpler and faster option.
  • If the string may contain non-numeric characters or if custom conversion behavior is required,istringstreamis 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!