atoi() 将整数的字符串表示形式转换为其值。它不会将任意字符转换为其十进制值。例如:
int main(void)
{
const char *string="12345";
printf("The value of %s is %d\n", string, atoi(string));
return 0;
}
标准 C 库中没有任何内容可以将“A”转换为 65 或“Z”转换为 90,您需要自己编写,特别是对于您期望作为输入的任何字符集。
既然您知道 atoi() 做了什么,请不要使用它来处理您想出的任何数字输入。你真的应该处理不是你所期望的输入。 嗯,当我输入 65 而不是 A 时会发生什么? 老师喜欢破坏东西。
atoi() 不做任何错误检查,这使得任何依赖它来转换任意输入的东西充其量都是脆弱的。相反,请使用strtol()(以 POSIX 为中心的示例):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
static const char *input ="123abc";
char *garbage = NULL;
long value = 0;
errno = 0;
value = strtol(input, &garbage, 0);
switch (errno) {
case ERANGE:
printf("The data could not be represented.\n");
return 1;
// host-specific (GNU/Linux in my case)
case EINVAL:
printf("Unsupported base / radix.\n");
return 1;
}
printf("The value is %ld, leftover garbage in the string is %s\n",
// Again, host-specific, avoid trying to print NULL.
value, garbage == NULL ? "N/A" : garbage);
return 0;
}
运行时,会给出:
值为123,剩余垃圾在
字符串是 abc
如果您不关心保存/检查垃圾,可以将第二个参数设置为NULL。不需要free(garbage)。另请注意,如果您将 0 作为第三个参数传递,则假定输入是十进制、十六进制或八进制表示的所需值。如果您需要 10 的基数,请使用 10 - 如果输入不符合您的预期,它将失败。
您还需要检查 long int 可以处理的最大值和最小值的返回值。但是,如果返回任何一个以指示错误,则设置 errno。读者的练习是将*input 从123abc 更改为abc123。
检查退货很重要,因为您的示例显示了如果不这样做会发生什么。 AbcDeFg 不是整数的字符串表示形式,您需要在函数中处理它。
对于您的实施,我能给您的最基本建议是一系列开关,例如:
// signed, since a return value of 0 is acceptable (NULL), -1
// means failure
int ascii_to_ascii_val(const char *in)
{
switch(in) {
// 64 other cases before 'A'
case 'A':
return 65;
// keep going from here
default:
return -1; // failure
}
.. 然后循环运行。
或者,预先填充一个查找函数可以作用域的字典(更好)。您不需要哈希,只需要一个键 -> 值存储,因为您提前知道它将包含什么,其中标准 ASCII 字符是键,它们对应的标识符是值。