首页  >  文章  >  后端开发  >  c++中 string转int的方法

c++中 string转int的方法

下次还敢
下次还敢原创
2024-05-01 13:27:16946浏览

在 C 中,有两种将 string 转换为 int 的方法:使用 sto i() 函数,直接接收字符串并返回整数。使用 istringstream 类,将字符串解析为输入流,然后提取整数。选择方法取决于字符串格式:如果格式明确且无非数字字符,stoi() 更简洁;如果字符串可能包含非数字字符或需要自定义转换,则 istringstream 更灵活。

c++中 string转int的方法

C 中 string 转 int 的方法

在 C 中,将字符串 (string) 转换为整数 (int) 有以下两种方法:

1. stoi() 函数

使用内置的 stoi() 函数是最简单直接的方法。它接收一个字符串参数并返回一个整数。

<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. istringstream

另一种方法是使用 istringstream 类。它将字符串解析为输入流,然后可以使用 运算符提取整数。

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

选择哪种方法?

  • 如果字符串格式明确,并且不包含任何非数字字符,则 stoi() 函数是更简单、更快的选择。
  • 如果字符串可能包含非数字字符或需要自定义转换行为,则 istringstream 更灵活。

以上是c++中 string转int的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn