如何将 std::string 转换为 int?

新手上路,请多包涵

我想将字符串转换为 int,我不是指 ASCII 码。

为了快速浏览,我们以字符串的形式传入一个方程。我们要将其分解,正确格式化并求解线性方程。现在,这么说,我无法将字符串转换为 int。

我知道字符串将采用 (-5) 或 (25) 等格式,所以它绝对是一个 int。但是我们如何从字符串中提取它呢?

我在想的一种方法是在字符串中运行 for/while 循环,检查一个数字,然后提取所有数字,然后查看是否有前导“-”,如果有,将 int 乘以 - 1.

不过,对于这样一个小问题,它似乎有点过于复杂。有任何想法吗?

原文由 Brandon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 584
2 个回答

在 C++11 中有一些不错的新转换函数,从 std::string 到数字类型。

所以而不是

atoi( str.c_str() )

您可以使用

std::stoi( str )

其中 str 是您的号码 std::string

有各种数字的版本: long stol(string)float stof(string)double stod(string) ,…见 http://en.cppreference.com/w/c /string/basic_string/stol

原文由 tgmath 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 C++11 中,我们可以使用 “stoi” 函数将字符串转换为 int

 #include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "16";
    string s2 = "9.49";
    string s3 = "1226";

    int num1 = stoi(s1);
    int num2 = stoi(s2);
    int num3 = stoi(s3);

    cout << "stoi(\"" << s1 << "\") is " << num1 << '\n';
    cout << "stoi(\"" << s2 << "\") is " << num2 << '\n';
    cout << "stoi(\"" << s3 << "\") is " << num3 << '\n';

    return 0;
}

原文由 Manish Kumawat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题