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

Ali Bigham picture Ali Bigham · Nov 10, 2012 · Viewed 16.5k times · Source

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;
}

Answer

Omkant picture Omkant · Nov 10, 2012

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