atoi() - 从char到int

时间:2015-05-05 21:56:53

标签: c++ atoi

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

我不知道为什么atoi()不起作用。编译器错误是:

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

我需要将c转换为int。

2 个答案:

答案 0 :(得分:2)

char已隐式转换为int

array[1][nood] = c;

但是,如果您想将char '0'转换为int 0,则必须利用C ++标准要求数字是连续的这一事实。来自[lex.charset]:

  

两者都有   源和执行基本字符集,在上面的小数列表中0之后的每个字符的值   数字应大于前一个数值。

所以你只需要减去:

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

答案 1 :(得分:0)

atoi()期望const char*映射到c string作为参数,您传递简单的char。因此,错误const char*表示指针,该指针与char不兼容。

看起来您只需要将一个字符转换为数字值,在这种情况下,您可以将atoi(c)替换为c-'0',这将为您提供0到9之间的数字。但是,如果你的文件包含十六进制数字,逻辑变得有点复杂,但并不多。

相关问题