我正在尝试处理来自 stdin 的输入,但一直碰壁。我的目标是阅读一串数字(0-99)并用文字打印每个数字。我的第一次尝试是:
int main(void) {
char *a[20] = {"zero","one","two","three","four","five","six","seven","eight",
"nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
"seventeen","eighteen","nineteen"};
char *b[8] = {"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
int num=0, tens=0, ones=0;
while (scanf("%d", &num)==1){
tens = num/10;
ones = num%10;
if (tens>1){
printf("%s ", b[tens-2]);
printf("%s \n", a[ones]);
}
else
printf("%s \n", a[num]);
}
printf("done");
return 0;
}
输出是正确的,但 scanf 从未终止循环。
第二次尝试:
int main(void) {
char *a[20] = {"zero","one","two","three","four","five","six","seven","eight",
"nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
"seventeen","eighteen","nineteen"};
char *b[8] = {"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
char line[1024], *ptr = NULL;
long num;
int tens=0, ones=0;
if(fgets(line, sizeof(line), stdin)!=NULL){
do {
num = strtol(line, &ptr, 10);
tens = num/10;
ones = num%10;
if (tens>1){
printf("%s ", b[tens-2]);
printf("%s \n", a[ones]);
}
else
printf("%s \n", a[num]);
}while (*ptr!= '\n');
}
printf("done");
return 0;
}
这里编译报错,找不到问题,不知道能不能行。
[UPDATE]:第二个代码运行但是输入了一个以上的数字,比如12 35 51 它无限打印第一个数字(十二)。
如有任何帮助,我们将不胜感激。
你很亲近。您只需要验证 strtol
的返回值,并在调用 strtol
之后根据 endptr
更新指针地址。您还应该检查讨论中提到的转换范围之外的值。这就是所有需要的:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void) {
char *a[] = {"zero","one","two","three","four","five","six",
"seven","eight","nine","ten","eleven","twelve",
"thirteen","fourteen","fifteen","sixteen",
"seventeen","eighteen","nineteen"};
char *b[] = {"twenty","thirty","fourty","fifty","sixty",
"seventy","eighty","ninety"};
char line[1024] = "";
long num;
int tens=0, ones=0;
if (fgets (line, sizeof(line), stdin) != NULL) {
char *p = line, *ep = NULL;
errno = 0;
while (errno == 0) {
num = strtol (p, &ep, 10); /* convert to long */
if (p == ep) break; /* no digits, break */
p = ep; /* update p to ep */
if (num < 0 || 99 < num) { /* validate range */
fprintf (stderr, "error: %ld - out of range.\n", num);
continue;
}
tens = num/10;
ones = num%10;
if (tens > 1) {
printf ("%s ", b[tens-2]);
printf ("%s \n", a[ones]);
}
else
printf("%s \n", a[num]);
}
}
printf ("done\n");
return 0;
}
示例使用/输出
$ ./bin/n2string
12 55 61 -1 33 102 4
twelve
fifty five
sixty one
error: -1 - out of range.
thirty three
error: 102 - out of range.
four
done
仔细阅读,如果您有任何问题,请告诉我。
我是一名优秀的程序员,十分优秀!