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

C++ 在C+中将字符串转换为int+;,c++,string,integer,C++,String,Integer,我有一个字符串xxxxxxxxxxxxxxxx 我将字符串读入一个由较小字符串组成的结构中,并使用substr对其进行解析。 我需要将其中一种字符串类型转换为整数 atoi不适合我,。有什么想法吗?它表示无法将std::string转换为const char* 谢谢 #include<iostream> #include<string> using namespace std; void main(); { string s="453"

我有一个字符串
xxxxxxxxxxxxxxxx

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

atoi
不适合我,。有什么想法吗?它表示
无法将std::string转换为const char*

谢谢

#include<iostream>

#include<string>

using namespace std;

void main();

{
    string s="453"

        int y=atoi(S);
}
#包括
#包括
使用名称空间std;
void main();
{
字符串s=“453”
int y=atoi(S);
}
需要
常量字符*
才能传入

将其更改为:

int y = atoi(s.c_str());
或者使用可以直接传递
字符串的:

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
}
#包括
#包括
使用名称空间std;
int main()
{
字符串s=“453”;
int y=atoi(s.c_str());
//int y=stoi(s);//另一种方法
}

C++中的情况很重要,如果你声明你的字符串为“代码> S/SCODE”,你需要在调用它时使用<代码> s < /> >不是<代码> >代码>,你也缺少一个分号来标记指令的结尾,在上面, Atoi 将<代码> char */COD>作为参数而不是字符串,因此,您需要传入一个char数组或指向char数组的指针:

函数签名:
intatoi(constchar*str)

更新:

#include<cstdlib>
#include<iostream>
#include<string>

using namespace std;

void main()    // get rid of semicolomn here 
{
    string s="453"; // missing ;
    int y=atoi(s.c_str());  // need to use s not S
    cout << "y =\n";
    cout << y;
    char e;     // this and the below line is just to hold the program and avoid the window/program to close until you press one key.
    cin  >> e;  
}
#包括
#包括
#包括
使用名称空间std;
void main()//在这里去掉半彩色
{
字符串s=“453”;//缺失;
int y=atoi(s.c_str());//需要使用s而不是s
库特;
}
#包括
int-toInt(std::string-str)
{
int-num;
std::stringstream ss(str);
ss>>num;
返回num;
}

atoi
不是一个很好的函数,如果您需要验证它是否成功转换,最好使用
strtol
:当我编写代码时,此错误提示错误C2447:“{”:缺少函数头(旧式正式列表?)你需要包括你的atoi函数所属的任何头,并且你需要确保你包括你所使用的任何函数的头。看看更新的代码。非常感谢你的帮助
#include<cstdlib>
#include<iostream>
#include<string>

using namespace std;

void main()    // get rid of semicolomn here 
{
    string s="453"; // missing ;
    int y=atoi(s.c_str());  // need to use s not S
    cout << "y =\n";
    cout << y;
    char e;     // this and the below line is just to hold the program and avoid the window/program to close until you press one key.
    cin  >> e;  
}
#include <sstream>

int toInt(std::string str)
{
    int num;
    std::stringstream ss(str);
    ss >> num;
    return num;
}