【发布时间】:2023-03-08 15:10:01
【问题描述】:
我正在尝试用 C 语言编写一个程序,用户输入如下:“一百九十九”,对于三位数字(直到一百),输出将是 199。
但我只有这个可以从 1 到 9 转换,我不知道如何实现更大的数字。
#include <stdio.h>
#include <string.h>
int main() {
char numbers[10][10] = {"zero", "one" , "two", "three","four", "five", "six", "seven","eight", "nine"};
char input[100], word[10], *ptr, *tmp;
int i, len, value;
int values[9];
/* get the number in words from user */
printf("Enter number in word:\n");
fgets(input, 100, stdin);
input[strlen(input) - 1] = '\0';
tmp = input;
while (1) {
/* move pointer to the space to extract word by word */
ptr = strchr(tmp, ' ');
if (ptr != NULL) {
len = ptr - tmp;
strncpy(word, tmp, len);
word[len] = '\0';
tmp = ptr + 1;
} else {
/* last word in the given string */
len = strlen(tmp);
strncpy(word, tmp, len);
word[len] = '\0';
}
for (i = 0; i < 10; i++) {
/* word to number conversion */
if (strcasecmp(word, numbers[i]) == 0) {
value = (value * 10) + i;
break;
}
}
if (!ptr)
break;
}
/* print the number */
printf("Value in number is %d\n", value);
int iN = 9;
int arr[iN];
while (iN--) {
arr[iN]=value%10;
value/=10;
}
printf("Value: %i", arr[0]);
return 0;
}
【问题讨论】:
-
我猜你必须编写一个编译器来解决这个问题,我想你可以用一个 c 程序来做这个,但这需要你一些时间。
-
您的输入总是三位数还是您也需要支持两位数?您需要支持的最小和最大数字是多少?
-
@JVMATL Off-by-1。你的评论是关于
input[strlen(input) - 0] = '\0';。 OP 正在使用input[strlen(input) - 1] = '\0';删除'\n',它是黑客可利用的,因为input[0]可能为0。 -
len = ptr - tmp; strncpy(word, tmp, len); word[len] = '\0';是 UB,输入类似于"abcdefghij"。希望您的用户只输入预期的输入。