stupid c code problem

All off topic discussions go here. Everything from the funny thing your cat did to your favorite tv shows. Non-programming computer questions are ok too.
Post Reply
GLneo

stupid c code problem

Post 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;
}
durand
Member
Member
Posts: 193
Joined: Wed Dec 21, 2005 12:00 am
Location: South Africa
Contact:

Re:stupid c code problem

Post 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?
GLneo

Re:stupid c code problem

Post 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:)
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:stupid c code problem

Post 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.
Every good solution is obvious once you've found it.
Post Reply