尝试将const char *转换为long long时程序崩溃

时间:2013-02-14 05:47:59

标签: c++

当程序运行时,它会长时间崩溃thisLong = atoll(c);这有什么理由吗?

string ConvertToBaseTen(long long base4) {
    stringstream s;
    s << base4;
    string tempBase4;
    s >> tempBase4;
    s.clear();
    string tempBase10;
    long long total = 0;
    for (signed int x = 0; x < tempBase4.length(); x++) {
         const char* c = (const char*)tempBase4[x];
         long long thisLong = atoll(c);
         total += (pow(thisLong, x));
    }
    s << total;
    s >> tempBase10;
    return tempBase10;
}

1 个答案:

答案 0 :(得分:3)

atoll需要const char*作为输入,但tempBase4[x]仅返回char

如果要将字符串中的每个字符转换为十进制,请尝试:

for (signed int x = 0; x < tempBase4.length(); x++) {
   int value = tempBase4[i] -'0';
   total += (pow(value , x));
}

或者,如果您想将整个tempBase转换为long long

long long thisLong = atoll(tempBase4.c_str());
total += (pow(thisLong, x));