問文) 引数octで指定された文字列が表す8桁の8進数を10進数に変換する関数 int octtodec(char oct[8]) を作成し、負数が入力されるまで、入力された8進数を10進数に変換して出力するプログラムを作成せよ。入力された文字列が8進数でなかった場合、エラーを出力して再度入力を促すこと。
(例) user>a.out Input number (Oct) : 1234 oct:1234 → dec:668 Input number (Oct) : 9876 Error: 9876 is NOT an oct number. Input number (Oct) : -1 bye... user>
int
octtodec(char oct[8])
{
return strtol(oct, NULL, 8);
}
bool
is_oct(char *str)
{ /* strtol(3) returns 0 if given value is 0, or given value is wrong. */
return (str[0] == '0' || strtol(str, NULL, 8) != 0);
}
int
main(void)
{
for (;;) {
char buf[8];
int val;
for (;;) {
printf("Input number (Oct) : ");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0'; /* remove '\n' */
if (!is_oct(buf)) {
printf("Error: %s is NOT an oct number.\n",
buf);
continue;
} else
break;
}
if ((val = octtodec(buf)) < 0) {
printf("bye...\n");
break;
}
printf("oct: %s -> dec: %d\n", buf, val);
}