C++字符串转整型--atoi

先看一个例子:

#include<iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    string s ;cin>>s;
    int a = atoi(s);
    cout<<a<<endl;

    return 0;
}

上述程序报错,no matching function for call to 'atoi',将程序进行修改:

int main()
{
    string s ;cin>>s;
    int a = atoi(s.c_str());
    cout<<a<<endl;

    return 0;
}

正常通过,原因因为atoi是C语言中的一个函数,C++为了向C语言进行兼容,在string中提供了一种成员函数---c_str()。

c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同。这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。

猜你喜欢

转载自blog.csdn.net/weixin_39003229/article/details/82457623