Advertisement

help with a very simple c program

Started by April 27, 2002 03:06 AM
4 comments, last by Shenron 22 years, 6 months ago
hi i recently started learning c and i tried making this simple program and have been tearing my hair out trying to figure out whats wrong. can someone tell me what im doing wrong? what this program is supposed to do is say "hi" to anyone who uses the name jin and say "i dont know you" to every other name. the problem is if i enter the name "jin" i always get "Sorry, I dont know you." Thanks. #include <stdio.h> void main() { char name[20]; printf("Hi. Please enter your first name: "); scanf("%s",&name); if(name == ''jin'' || name == ''Jin'' || name == ''JIN'') printf("Hi Jin. I know you!\n"); else printf("Sorry, I don''t know you.\n"); }
You should use the function stricmp(char*,char*) it will return zero if the strings matchs, stricmp will make a case insensitive comparison of the strings. there is also a function called strcmp(char*,char*) which is case sensitive.

this is how your program should look:

...
if(stricmp("jin",name)==0) {
printf("Hello!");
} else {
printf("Goodbye!");
}
...
--------------------------------"I'm a half time coder, full time Britney Spears addict" Targhan
Advertisement
Hi there!

You can''t compare strings like that.
Try looking for strcmp or strcmpi functions in the reference. They help comparing strings.

Let us know what happened :D

SKeTch
SKeTch
the pointer to a string is already given by its name.
So, the pointer to char name[20];
is name and not &name.

so i think. try it.
I''m looking into those functions right now. Thanks so much guys
Another thing is that you were using '''' for your strings in the comparisions (which, as others have pointed out, you can''t do that way). Strings must be within "" (and a \0 is appended to the string constant), while single characters are within '''' (and the \0 isn''t appended). So if you wanted a string s, you would do


  // yeschar *s = "this is a null terminated string";// nochar *s = ''this is NOT a null terminated string'';  


Although this doesn''t answer your question, it is something to watch out for. If the single quote is just a typo, then just ignore this.


Mike

This topic is closed to new replies.

Advertisement