I am using user input to control a program. I have two arrays.
The first is a 1-D char array called controlWord
(this will store the users input).
The second is a 2-D array called promptWord
(an array of char arrays containing words which correspond to actions the code will preform)
char controlWord[100]; //control word compare it to promptWord
char promptWord[5][100]={"Add","Subtract","Multiply","Divide","?"}; //for program control
When the user is prompted for input I use gets()
to save the input into the first char array. Then I go and compare this char array to the second char array full of the potential prompt words the user might enter.
printf("\n\ncontrolword: ");
gets(controlWord);
if (strcmp(controlWord, promptWord[0]))//Add
{
//stuff
}else if (strcmp(controlWord, promptWord[1]))//Listen
{
//more stuff
}else
I don't want to search for a substring. I only want exact matches. Even after carefully inputting strings that should work I am getting an error. (especially with '?')
Edit:
As noted here "gets
/fgets
store the newline char, '\n' in the buffers also. If you compared the user input to a string literal such as "abc" it would never match"
So now I have a catch 22: I can use gets()
which is considered bad practice, or I can use fgets()
which will grab a new line character. I suppose I could go in and null out the last non-zero character, but what if my input is exactly 99 or 100 char long? I only have room for the first 100 char in my char array so how would I know if I had 99 char + a new line or 100 char and I lost the new line?
I'm looking for a solution which avoids gets
but is more elegant than the fgets
searching for a null character.