Mail Archives: djgpp/1997/07/22/23:50:55
James MacDonald wrote:
> At the moment I'm using scanf() - I need to read a value from the
> keyboard and compare it with a generated one made by a program.
>
> Here's the code :
>
> char * enter;
>
> scanf("%s", enter);
> printf("Entered string : %s", enter);
> if (enter == chalcrypt) printf("it worked!");
>
> For entered string, '(null)' is displayed, and that only.
> What am I doing wrong?
You're not making sure your string has enough memory. In fact, you're not
initializing enter at all, so you've got a dangling pointer, and should be
grateful your program doesn't crash. (It's luck that it doesn't crash,
and furthermore, that enter just _happened_ to be 0.)
What you need to do is something like this:
char enter[256]; /* or however much is necessary */
scanf("%s", enter);
printf("Entered string: %s\n", enter);
Furthermore, you can't just compare strings with the == operator, because
that's only comparing the addresses of the pointers, which will never
work. You need to use strcmp:
if (strcmp(enter, chalcrypt) == 0) printf("It worked!\n");
> Is there an easier way to read the keyboard?
> I've tried gets() but I've got stuck there too :(
For the same reason. I strongly suggest you use get a good ANSI C book
and read up on arrays, pointers, and strings.
--
Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
Alcyone Systems / web / http://www.alcyone.com/max/
San Jose, California, United States / icbm / 37 20 07 N 121 53 38 W
\
"Love is not love which alters / when it alternation finds."
/ William Shakespeare, _Sonnets_, 116
- Raw text -