Write a C program to convert words into numbers.
#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, value = 0, len;
/* 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);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter number in word:
one four three six nine
Value in number is 14369
Enter number in word:
one four three six nine
Value in number is 14369
No comments:
Post a Comment