将字符数字转换为C中的相应整数 [英] Convert a character digit to the corresponding integer in C
本文介绍了将字符数字转换为C中的相应整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以将字符转换为C中的整数?
Is there a way to convert a character to an integer in C?
例如,从'5'
到5?
推荐答案
根据其他答复,这很好:
As per other replies, this is fine:
char c = '5';
int x = c - '0';
此外,对于错误检查,您可能希望首先检查isdigit(c)是否为true.请注意,您不能完全便携地对字母执行相同的操作,例如:
Also, for error checking, you may wish to check isdigit(c) is true first. Note that you cannot completely portably do the same for letters, for example:
char c = 'b';
int x = c - 'a'; // x is now not necessarily 1
该标准保证数字'0'至'9'的char值是连续的,但不保证其他字符(例如字母).
The standard guarantees that the char values for the digits '0' to '9' are contiguous, but makes no guarantees for other characters like letters of the alphabet.
这篇关于将字符数字转换为C中的相应整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文