在C ++中将字符串转换为int

在C ++中将字符串转换为int

问题描述:

我有一个字符串xxxxxxxxxxxxxxxxxxx

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

I am reading the string into a structure of smaller strings, and using substr to parse it. I need to convert one of those string types to integer.

atoi对我不起作用.有任何想法吗?它说cannot convert std::string to const char*

atoi is not working for me,. any ideas? it says cannot convert std::string to const char*

谢谢

#include<iostream>

#include<string>

using namespace std;

void main();

{
    string s="453"

        int y=atoi(S);
}

要求const char *传递.

将其更改为:

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

或使用 std::stoi() ,您可以通过直接:

or use std::stoi() which you can pass a string directly:

int y = stoi(s);


您的程序还有其他几个错误.可行的代码可能类似于:


You program has several other errors. Workable code could be something like:

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

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