21xrx.com
2025-07-08 20:15:07 Tuesday
文章检索 我的文章 写文章
C++字符串转换为整型的方法
2023-07-06 08:16:26 深夜i     17     0
C++ 字符串 转换 整型 方法

在C++中,字符串和整型之间的转换是常见的操作。为了把一个字符串转换为整型,我们需要使用C++标准库中的函数。下面是一些将字符串转换为整型的方法:

1. 使用std::stoi()函数

std::stoi()函数可以将一个字符串转换为int类型。它接受一个字符串参数和一个可选的进制数。如果第二个参数没有提供,则默认为十进制。

例如,下面的代码将一个字符串转换为整型:

#include <iostream>
#include <string>
int main() {
  std::string str = "1234";
  int num = std::stoi(str);
  std::cout << "Converted number is: " << num << std::endl;
  return 0;
}

输出结果:

Converted number is: 1234

2. 使用stringstream

stringstream是一个流,它可以将字符串转换为其他类型,如int、float、double等。通过使用stringstream,我们可以使用类似于cin的方式来输入字符串并将其转换为int类型。

例如,下面的代码将一个字符串转换为整型:

#include <iostream>
#include <sstream>
#include <string>
int main() {
  std::string str = "1234";
  std::stringstream ss(str);
  int num;
  ss >> num;
  std::cout << "Converted number is: " << num << std::endl;
  return 0;
}

输出结果:

Converted number is: 1234

3. 使用字符数组

将字符串转换为整型的另一种方法是使用字符数组。这种方法可以将字符串转换为数字,从而避免了使用标准库函数的开销。

例如,下面的代码将一个字符串转换为整型:

#include <iostream>
#include <string>
int main() {
  std::string str = "1234";
  char char_arr[str.length() + 1];
  strcpy(char_arr, str.c_str());
  int num = 0;
  for (int i = 0; i < str.length(); i++) {
    num = num * 10 + (char_arr[i] - '0');
  }
  std::cout << "Converted number is: " << num << std::endl;
  return 0;
}

输出结果:

Converted number is: 1234

总结:

以上是三种将字符串转换为整型的方法。第一种方法是使用C++标准库函数std::stoi(),第二种方法是使用stringstream,第三种方法是使用字符数组。无论使用哪种方法,我们都可以将一个字符串转换为整型,在C++编程中应用广泛,有助于提高程序的效率和可读性。

  
  

评论区