-->

use of atoi() function in c++

2019-09-23 20:09发布

问题:

when I pass a string variable in the below code, g++ gives an error:

cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

My code is:

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    string a = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}

But if I change the code to :

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    char a[3] = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}

It works completely fine.

Please explain why string doesn't work. Is there any difference between string a and char a[]?

回答1:

atoi is an older function carried over from C.

C did not have std::string, it relied on null-terminated char arrays instead. std::string has a c_str() method that returns a null-terminated char* pointer to the string data.

int b = atoi(a.c_str());

In C++11, there is an alternative std::stoi() function that takes a std::string as an argument:

#include <iostream>
#include <string>

int main()
{
    std::string a = "10";
    int b = std::stoi(a);
    std::cout << b << "\n";
    return 0;
}


回答2:

You need to pass a C style string.

I.e use c_str()

Change

int b = atoi(a);

to

int b = atoi(a.c_str());

PS:

This would be better - get the compiler to work out the length:

char a[] = "10";


回答3:

atoi() expects a null-terminated char* as input. A string cannot be passed as-is where a char* is expected, thus the compiler error. On the other hand, a char[] can decay into a char*, which is why using a char[] works.

When using a string, call its c_str() method when you need a null-terminated char* pointer to its character data:

int b = atoi(a.c_str());


回答4:

according to the documentation of atoi(), the function expects a "pointer to the null-terminated byte string to be interpreted" which basically is a C-style string. std::string is string type in C++ but it have a method c_str() that can return a C-string which you can pass to atoi().

string a = "10";
int b = atoi(a.c_str());

But if you still want to pass std::string and your compiler supports C++ 11, then you can use stoi()

string a = "10";
int b = stoi(a);


标签: c++ atoi