Search code examples
c++atoi

atoi() - from char to int


char c;
int array[10][10];
while( !plik.eof())
{
    getline( plik, text );
    int string_l=text.length(); 
    character_controler=false;
    for(int i=0; i<string_l; ++i)
    {
        c=napis.at(i);
        if(c==' ') continue;
        else if(character_controler==false)
        {
            array[0][nood]=0;
            cout<<"nood: "<<nood<< "next nood "<<c<<endl;
            array[1][nood]=atoi(c); // there is a problem
            character_controler=true;
        }
        else if(c==',') character_controler=false;
    }   
    ++nood;
}

I have no idea why atoi() doesn't work. The compiler error is:

invalid conversion from `char` to `const char*`

I need to convert c into int.


Solution

  • A char is already implicitly convertible to an int:

    array[1][nood] = c;
    

    But if you meant to convert the char '0' to the int 0, you'll have to take advantage of the fact that the C++ standard mandates that the digits are contiguous. From [lex.charset]:

    In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

    So you just have to subtract:

    array[1][nood] = c - '0';