性格整数用C [英] Character to Integer in C

查看:114
本文介绍了性格整数用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为一个字符转换为C中的整数?

Is there a way to convert a character to an integer in C?

例如,
'5' - > 5

for example, '5' -> 5

感谢。

推荐答案

按照对方回复,这是罚款:

As per other replies, this is fine:

char c = '5';
int x = c - '0';

此外,对于错误检查,你不妨检查一下ISDIGIT(c)是真正的第一。请注意,你不能完全可移植做字母相同的,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆