C programming loop help?

Question by boxinggirl24: C programming loop help?
im writing a program which needs the password ‘cs’ to end the loop what i have right now is:

#include

int
main (void)
{
char first;
char second;

printf(“Enter password: “);
scanf(“%c%c”, &first, &second);

while(first != ‘c’ || second != ‘s’){
printf(“incorrect, try again: “);
scanf(“%c%c”, &first, &second);
}

printf (“Door Unlocked”);

return (0);
}

the problem is every other time a password is entered it prints “incorrect, try again: incorrect, try again: ” and only on the times when it is printed twice like so does the correct password of ‘cs’ end the loop, how can i fix this?

Best answer:

Answer by Mantis
What you should do is read in the password as a string rather than two characters. I would use GetLine instead of scanf. You can then check that input[0] == ‘c’ && input[1] == ‘s’. That should clear up the problem.

Good luck.

Know better? Leave your own answer in the comments!

3 comments

  1. It works fine for me the first time. If you miss the first attempt, though, the character scanned for &first in the second scanf() call will be ‘n’ probably,

    It might be easier to scan in a string (with max length limits, of course), as in

    #include

    char answer[82];

    scanf(“%80s”, answer);
    while (strcmp(“cs”, answer) != 0)
    {
    printf(“incorrect; try again: “);
    scanf(“%80s”, answer);
    }

    Be sure to protect your program when you use scanf for strings. Always put the maximum buffer size in, as in “%80s” instead of “%s”. The second form is vulnerable to buffer overruns. So is the first, if you specify too large a buffer size.

  2. Agree with Mantis, you should read a line at a time here, not 2 chars.

    But it’s helpful to understand why this fails:

    When you enter the password, you have to hit 3 keys:
    c
    s

    Scanf will put c into first, s into second, AND LEAVE THE ENTER KEY IN THE INPUT BUFFER.

    So now what happens when you use the wrong password
    x y
    first is x
    second is y
    enter (n) is still in the input buffer.
    You print the error message and try again with:
    c s

    But there is still a n char in the input buffer, so:
    first is n
    second c

    Now there’s an s and a n left in the input buffer, and you think the password was wrong.

    So, yes, read the entire line, so you don’t have to deal with junk left in the input buffer.

  3. Put some printf() debugging statements in to print out the obtained values of first and second after each scanf(). You might be surprised at what’s getting in.

    A tip: Surround each character echo with a marker character, so white-space and end-of-lines don’t disappear. In other words, use something like this:

    printf( “first character: < %c>n”, first );
    printf( “second character: < %c>n”, second );

    Hope that helps.

Leave a Reply

Your email address will not be published. Required fields are marked *