21xrx.com
2024-09-17 04:10:24 Tuesday
登录
文章检索 我的文章 写文章
C++中如何将字符串转换为整数?
2023-07-14 09:57:17 深夜i     --     --
C++ 字符串 转换 整数

在C++中,开发人员通常需要将字符串转换为整数。在今天的教程中,我们将学习如何实现这一功能。首先,我们需要了解C++中已经内置的两个函数:stoi和atoi。

1. atoi函数

atoi函数可以将字符串转换为整数。以下是一个使用示例:


#include <iostream>

#include <cstdlib>

int main() {

  const char* str = "42";

  int num = std::atoi(str);

  std::cout << "The integer is " << num << std::endl;

  return 0;

}

输出结果为:


The integer is 42

2. stoi函数

与atoi函数类似,stoi函数可以将字符串转换为整数。以下是一个使用示例:


#include <iostream>

#include <string>

int main() {

  const std::string str = "42";

  int num = std::stoi(str);

  std::cout << "The integer is " << num << std::endl;

  return 0;

}

输出结果为:


The integer is 42

需要注意的是,如果在转换时字符串中包含非数字字符,这两个函数都会抛出异常。如果你想避免异常,可以使用第三种方法。

3. 从字符串中提取数字

我们可以使用字符串流来从字符串中提取数字,这可以避免抛出异常。以下是一个使用示例:


#include <iostream>

#include <string>

#include <sstream>

int main() {

  const std::string str = "42";

  int num;

  std::stringstream ss(str);

  ss >> num;

  std::cout << "The integer is " << num << std::endl;

  return 0;

}

输出结果为:


The integer is 42

总结

在C++中,我们可以使用atoi和stoi函数将字符串转换为整数。但是,这两个函数可能会抛出异常。如果你想避免异常,可以使用字符串流来提取数字。现在你已经学会了如何将字符串转换为整数了,赶快去实践吧!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复