如何将C++ string 类型的每一位字符转换成int(并不是将整个string转换成int)?


string str ="123456";
如何把str的每一位str[i]转换成数字?

已经尝试:
用int(str[i])只能得到ascii码。
用atoi(str.c_str())也只能将整个string转换成int。

类型转换 C++

asdc110 8 years, 10 months ago

 #include <string>
#include <stdlib.h>

using namespace std;


int main(){
    string str = "123456";
    const char *p = str.c_str();
    for (int i = 0; i < str.length(); i++)
    {
        int a = str[i] - '0';
        printf("%d \n", a);

    }
    system("pause");
    return 0;
}

空空D木偶 answered 8 years, 10 months ago

你都得到ASCII码了,减去'0'(也就是48)不就是数字了么……

liuxue answered 8 years, 10 months ago

Your Answer