我编写的程序在只包含单个十六进制值的人口统计中工作。(可能不是最优雅的解决方案,但我是一个新程序员)我的问题是,我该如何处理多个十六进制数字,如0xAF或0xFF等?我不是很确定,而且在尝试的过程中,我似乎把自己搞糊涂了。我并不是要求有人拉着我的手,而是给我一个提示,告诉我在这段代码中我哪里出了问题,以及如何修复它。
谢谢:)
/* Exercise 2-3. Write the function htoi(s), which converts a string of
* hexadecimal digits (including an optional 0x or 0X) into it's equivalent
* integer value. The allowable digits are 0...9 - A...F and a...f.
*
*/
#include <stdio.h>
#include <string.h>
#define NL '\n'
#define MAX 24
int htoi(char *hexd);
int
main(void)
{
char str[MAX] = {0};
char hex[] = "0123456789ABCDEFabcdef\0";
int c;
int i;
int x = 0;
while((c = getchar()) != EOF) {
for(i = 0; hex[i] != '\0'; i++) {
if(c == hex[i])
str[x++] = c;
}
if(c == NL) {
printf("%d\n", htoi(str));
x = 0, i = x;
}
}
return 0;
}
int
htoi(char *hexd)
{
int i;
int n = 0;
for(i = 0; isdigit(hexd[i]); i++)
n = (16 * i) + (hexd[i] - '0');
for(i = 0; isupper(hexd[i]); i++) /* Let's just deal with lowercase characters */
hexd[i] = hexd[i] + 'a' - 'A';
for(i = 0; islower(hexd[i]); i++) {
hexd[i] = hexd[i] - 'a';
n = (16 + i) + hexd[i] + 10;
n = hexd[i] + 10;
}
return n;
}发布于 2009-04-30 06:25:08
我将选择一个循环,并让您重新考虑您的实现。具体地说:
for(i = 0; isdigit(hexd[i]); i++)
n = (16 * i) + (hexd[i] - '0');不会像你想的那样...
isdigit()为TRUE的第一个字符。isdigit()为FALSE的第一个字符上停止。isdigit('\0')为FALSE。不过,我担心这可能是偶然正确的。整个程序需要考虑的事情:
htoi("1234")的用户正在调用未定义的行为。你真的不想这样做,只有一个遍历数字的循环会处理非零位数的数字,如果我向stdin0123456789ABCDEF0123456789ABCDEF,会发生什么,你希望在80000000中得到吗?,,,
,
0123456789ABCDEF0123456789ABCDEF,,
80000000中得到的是什么?你得到了什么?你是我不会使用NL surprised?'\n'。C语言的使用很可能会在宏不方便使用的很多上下文中看到\n,所以最好现在就习惯它……https://stackoverflow.com/questions/805049
复制相似问题