在字符串到 int 转换中使用 atoi 时出错

error in using atoi in string to int conversion

本文关键字:atoi 出错 字符串 int 转换      更新时间:2023-10-16

因此,我尝试使用atoi函数将字符串转换为int,但是我收到一个错误,指出参数类型char与const char*类型的参数不兼容。 这是代码:

void evaluate(const char values[], string& codeMessage, string& result)
{
    unsigned int i = 0;
    while (i<codeMessage.length())
    {
        result+= values[atoi(codeMessage[i])];
        i++;
    }
}

因此,如果调用函数evaluate({a,b,c,d}, "2331", result),则结果必须包含"cdda"。 知道吗,我的代码有什么问题? 谢谢

atoi需要一个 C 字符串,而不是单个字符。

如果你想在词法上将一个数字转换为等效的整数,为什么不简单地断言它在 '0''9' 之间,然后减去'0'?无论区域设置的字符集如何,数字都必须是连续的。

while (i < codeMessage.length()) {
    if (codeMessage[i] >= '0' && codeMessage[i] <= '9') {
       result += values[codeMessage[i] - '0'];
    }
    i++;
}