読み込んだ文字列が10進数かそうでないかを判定する関数
なので true か false、すなわち 1 か 0 を返せばよいはず
なのになぜ、10を返すのでしょうか?
C の整数定数のような 16進定数や 8進定数も判別したかった]
のでしょうか?
コード:
#include <stdio.h>
int isHex(unsigned char c)
{
return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
}
int getBase(const char *p)
{
if (*p == '-' || *p == '+') p++;
if (*p >= '1' && *p <= '9') {
while (*++p >= '0' && *p <= '9') ;
return *p ? 0 : 10;
}
if (*p == '0') {
if (*++p == 'x' || *p == 'X') {
if (!isHex(*++p)) return 0;
while (isHex(*++p)) ;
return *p ? 0 : 16;
}
while (*++p >= '0' && *p <= '7') ;
return *p ? 0 : 8;
}
return 0;
}
int main(void)
{
char str[100];
while (1) {
printf("Enter a character string: ");
if (scanf("%99s", str) != 1 || str[0] == '.') return 0;
switch (getBase(str)) {
case 10: printf(" \"%s\" is a decimal number\n", str); break;
case 16: printf(" \"%s\" is a hexadecimal number\n", str); break;
case 8: printf(" \"%s\" is an octal number\n", str); break;
default: printf(" \"%s\" is not a number\n", str);
}
}
return 0;
}
実行例
コード:
Enter a character string: -123
"-123" is a decimal number
Enter a character string: 0123
"0123" is an octal number
Enter a character string: 0x123
"0x123" is a hexadecimal number
Enter a character string: x123
"x123" is not a number
Enter a character string: .
本当の C の整数定数には符号は付きません。
また u や LL などの接尾語が付くことがあります。