Looks like you need some pointers.
First, here's an easier way to create an array of the word numbers:
Code:
char *nums[10] = { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
nums is an array of string literals. That means it has to be defined (assigned values) when it is declared (as above). Generally you should not try and modify a string literal after the declaration.
Next, you cannot compare strings this way:
The easiest way is to use strcmp() from string.h. Strcmp() returns 0 when it's two parameters are identical. I suggest you look up this and the other new commands from this post in whatever reference you are using in order to make sure you understand them. Now lets put a few things together:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char *nums[10] = { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" }, input[16];
int i;
while (1) {
printf("Enter a number: ");
fgets(input,16,stdin);
if (input[0] == 'q') return 0; // q to quit
if (sscanf(input, "%[a-z]", input) != 1) {
puts("Invalid! Try again...");
continue;
}
for (i=0;i<10;i++) {
if (strcmp(nums[i],input) == 0) {
printf("digit = %d\n",i);
break;
}
if (i==9) printf("\"%s\" is not valid input.\n",input);
}
}
return 0;
}
"while(1)" is an infinite loop, because the condition is always true. You must kill the program, or enter "q" to get out of it.
I use fgets for the input because that's my personal preference (also: some methods are better than others ). However, this will include a "\n" (eg, "one\n", so to avoid that I rip a string of lower case characters from the raw input data with sscanf. That's the line in red. Notice you can read from, and read into, the same string variable with sscanf (or they could be two different variables). Sscanf, like all the "scan" type functions, returns the number of items successfully read. So if we do not find a lowercase word in "input", we throw an error to the user.
If everything works out, we do the strcmp() in a loop through the array of word numbers.
Try this out and ask questions if you want.