在C中将字符串转换为int

新手上路,请多包涵

我有一个字符串, xxxxxxxxxxxxxxxxxxx

我正在将字符串读入较小字符串的结构中,并使用 substr 对其进行解析。我需要将其中一种字符串类型转换为整数。

atoi 不适合我。我该怎么做?它说:

无法将 std::string 转换为 const char*

代码

#include <iostream>
#include <string>

using namespace std;

void main();
{
    string s = "453"

    int y = atoi(S);
}

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

阅读 586
1 个回答

std::atoi() 需要 const char * 才能传入。

将其更改为:

 int y = atoi(s.c_str());

或使用 std::stoi() 您可以直接传递 string

 int y = stoi(s);


您的程序还有其他几个错误。可行的代码可能是这样的:

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

int main()
{
    string s = "453";
    int y = atoi(s.c_str());
    // int y = stoi(s); // another method
}

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

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