当我不使用标准字符串时,如何将字符串转换为c ++中的int?

ube*_*ate 2 c++ string int

我正在构建自己的字符串类,我正在尝试使用此函数将数字字符串转换为整数:

int String::convertToInt() const {  
    int exp = length() - 1;
    int result = 0;

    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * (10 ^ exp);
        --exp;
    }   
    return result;
}
Run Code Online (Sandbox Code Playgroud)

有些东西不能正常工作,但我无法找出它是什么.当我尝试将"49"转换为int时,它将其转换为134.

Rei*_*ica 9

^异或.我相信你在找std::pow(10, exp).

甚至这个:

int String::convertToInt() const {  
    int order = std::pow(10, length() - 1);
    int result = 0;

    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * order;
        order /= 10;
    }   
    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 哎哟,这将是一个非常低性能的想法. (2认同)