简体   繁体   中英

Why atoi function can't convert const char * to int?

Why does in this code the atoi() function does not work properly and why does the compiler give this error:

initializing argument 1 of `int atoi(const char*)'

My code follows:

#include <iostream.h>
#include <stdlib.h>
int main()
{
    int a;
    char b;
    cin >> b;
    a = atoi(b);
    cout << "\na";  
    return 0;
}

b is char but in atoi() you must pass char * or const char * since c++ is strict type checking language hence you are getting this

It should be like this cout<<"\\n"<<a; not this cout<<"\\na" because the later one will not print the value of a

As you can see here atoi

Atoi receives a pointer to char, instead of a char like you did. And it makes sense because in this way you can apply atoi in an "number" (represented in a string) with more than 1 digit, for example atoi("100");

int atoi ( const char * str );

Otherwise, if it was a char, you could only convert '0','1','2'.. '9'.

EDIT: try this example:

#include <iostream>
#include <stdlib.h>
int main()
{
    int a;
    char b[10];


    cin >> b;
    a = atoi(b);

    cout<<"\n"<<a; 
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM