Home  >  Article  >  Backend Development  >  How to convert string to int in c++

How to convert string to int in c++

下次还敢
下次还敢Original
2024-05-01 13:27:16946browse

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-in stoi() function is the simplest and most direct Methods. It takes a string parameter and returns an integer.

<code class="cpp">#include <iostream>
#include <string>

int main() {
  std::string str = "123";
  int number = stoi(str);
  std::cout << "String: " << str << "\n";
  std::cout << "Integer: " << number << "\n";
  return 0;
}</code>

2. isringstream

Another way is to use the istringstream class. It parses the string into an input stream, from which integers can be extracted using the operator.

<code class="cpp">#include <iostream>
#include <sstream>

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;
}</code>

Which method to choose?

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

Statement:
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