如何在C和c++中将字符转换为int ?


当前回答

嗯,在ASCII码中,数字(数字)从48开始。你所需要做的就是:

int x = (int)character - 48;

或者,因为字符'0'的ASCII码是48,你可以这样写:

int x = character - '0';  // The (int) cast is not necessary.

其他回答

对于char或short to int,只需要赋值。

char ch = 16;
int in = ch;

与int64相同。

long long lo = ch;

所有值都是16。

int charToint(char a){
char *p = &a;
int k = atoi(p);
return k;
}

您可以使用此atoi方法将char转换为int。想了解更多信息,可以参考这个http://www.cplusplus.com/reference/cstdlib/atoi/, http://www.cplusplus.com/reference/string/stoi/。

嗯,在ASCII码中,数字(数字)从48开始。你所需要做的就是:

int x = (int)character - 48;

或者,因为字符'0'的ASCII码是48,你可以这样写:

int x = character - '0';  // The (int) cast is not necessary.

C和c++总是将类型提升到至少int。此外,字符字面量在C中是int类型,在c++中是char类型。

可以通过赋值给int类型来转换char类型。

char c = 'a'; // narrowing on C
int a = c;

使用static_cast < int >:

int num = static_cast<int>(letter); // if letter='a', num=97

编辑:你可能应该尽量避免使用(int)

Int num = (Int)字母;

为什么使用static_cast<int>(x)而不是(int)x?更多信息。