QUOTE(kvarnerexpress @ Feb 20 2006, 04:27 AM)

G'day D'day, first time posting and even my first time at the site (found after a quick google) so i hope i've followed the correct protocol. I'm stuck using borland C in Windows at home and i've come across a simple problem. My knowledge of C spans from the basics up to Stacks, Queues, Lists, Linked/Double versions, Binary tree and hash tables but its the simple things that always get me stumped.
The issue i'm having is that i use a fgets to recieve and store a string, followed by a strcmp with the saved string and "generic preset command" resulting in failed conditions. Right now the program i'm writing is a bit large so i've just written a small sample one to illustrate the problem:
Code:
PHP Code:
CODE
char array[20];
printf("Enter a string\n\n");
fgets(array,1024,stdin);
if(strcmp(array,"bob the builder")==0)
{
printf("%s is a valid command",array);
}
else
{
printf("Error: Unknown Command, try again");
}
It will always result in the error part of the loop and i'm fairly certain that the issue arises from fgets recieving one additional character, but i can't for the life of me remember how to go about it. I had a quick look around the FAQ (Which i applaud the posters for as it resolved many issues i've had) but couldn't find anything regarding this. Once again, awesome site full of answers to questions and issues i had a year ago with my comp sci course
What you said is correct, there is an additional character receive from fget. That is the newline character. Do you remember what is the last key when you input the command? That is the 'Enter' Key. So you have to include the newline character in your compare string. i.e. the compare string should be 'bob the builder
\n' instead of 'bob the builder'
CODE
char array[20];
printf("Enter a string\n\n");
fgets(array,1024,stdin);
if(strcmp(array,"bob the builder\n")==0)
{
printf("%s is a valid command",array);
}
else
{
printf("Error: Unknown Command, try again");
}
Actually, this problem can be solved if you run it in debug mode. Try to watch the variable and compare the strings manaully, you will found that 2 strings are somehow different.
Please also be noted that your array size is only 20 while fgets read in 1024 bytes, it may cause memory error if you input string is longer than 19.
Reply