Page 1 of 1
stupid c code problem
Posted: Fri Dec 16, 2005 4:37 pm
by GLneo
i have been writting an operating system so long i forgot stdio.h
what is wrong with this code:
Code: Select all
#include <stdio.h>
#include <stdlib.h>
int main()
{
char message[100];
char yes_no = 'y';
while(yes_no == 'y' | yes_no == 'Y')
{
printf("Enter your message: ");
scanf("%s", message);
printf(message);
printf("again???, [Y]es or [N]o:");
scanf("%c", &yes_no);
}
system("pause");
return 0;
}
Re:stupid c code problem
Posted: Fri Dec 16, 2005 5:08 pm
by durand
It's not just your stdio.h. You're using a bitwise OR instead of a logical one.
Code: Select all
while(yes_no == 'y' | yes_no == 'Y')
.. should be ..
while ( (yes_no == 'y') || (yes_no == 'Y') )
And your scanf can read more than 100 characters into your message variable.. creating a buffer overflow vulnerability.
Plus you're only reading a format string of "%s" which matches non-whitespace characters until a NULL character. Which is probably not what you want. Try "man scanf" if you're on a unix system or google for the man pages for scanf to get the correct format specifiers for the input you want to match.
Also, you could perhaps replace the system call with a getch() call?
Re:stupid c code problem
Posted: Fri Dec 16, 2005 5:45 pm
by GLneo
thx, about the bitwise OR *smack myself*
and my problem was : scanf("%c", &yes_no); why did this not work???
p.s. yes_no = getch(); does work thx:)
Re:stupid c code problem
Posted: Sun Dec 18, 2005 5:54 am
by Solar
You might have noticed that [tt]printf(message);[/tt] does not print a line break, although you
did enter a linebreak on input. That is because [tt]scanf("%s")[/tt] scans until the first
whitespace character. The linebreak is rejected by [tt]scanf()[/tt], and not added to [tt]message[/tt]. It is still in the input stream.
Your [tt]scanf("%c")[/tt], then, reads the linebreak, and doesn't wait for you to input y or n.
As always when your code confuses you, assert your assumptions. Obviously yes_no was filled with some strange value that was not "y" nor "Y". Changing:
Code: Select all
printf("again???, [Y]es or [N]o:");
scanf("%c", &yes_no);
}
to:
Code: Select all
printf("again???, [Y]es or [N]o:");
scanf("%c", &yes_no);
printf("%d\n", yes_no);
}
would have told you what value that is (10), and
that would probably have given you the clue.