1

So I'm trying to ask the user if they would like to repeat my program and I am getting a weird result now and then. It doesn't happen everytime and I havn't been able to figure out what triggers it.

To me it looks like it is assigning the 'return' after I enter 'q' to repeatProgram instead of the 'q' but I have no Idea why.

The output when it works:

to exit enter q, to continue enter y.
s
you've entered s, that isn't a valid option.

The output when it fails:

to exit enter q, to continue enter y.
q
you've entered
, that isn't a valid option.

The code:

char RepeatProgramPrompt()
{
    char repeatProgram;

    do
    {
        printf("\nTo exit enter q, to continue enter y.\n");
        scanf("%c%*c", &repeatProgram);

        repeatProgram = tolower(repeatProgram);

        if(repeatProgram != 'y' && repeatProgram != 'q')
        {
            printf("\nYou've entered %c, that isn't a valid option.\n", repeatProgram);

        }

    }while(repeatProgram != 'y' && repeatProgram != 'q');


    return(repeatProgram);
}

So my question is, why is this happening? it will work fine for a bunch of tries and then just fail.

Sorry if I've formatted this wrong it is my first post.

4

2 回答 2

0

Eat up the trailing whitespace characters with newline after scanf and it should work:

scanf("%c", &repeatProgram);
while(getchar() != '\n')
{
    //do nothing
}

Sample output.

于 2013-10-28T06:40:10.240 回答
0

That problem occurs because your scanf reads the \n after your first input. To avoid this change your scanf statement to this:

scanf("%c", &repeatProgram);
getchar(); // this will remove the excess '\n'

Output:

Sukhvir@Sukhvir-PC ~
$ ./test

To exit enter q, to continue enter y.
d

You've entered d, that isn't a valid option.

To exit enter q, to continue enter y.
s

You've entered s, that isn't a valid option.

To exit enter q, to continue enter y.
d

You've entered d, that isn't a valid option.

To exit enter q, to continue enter y.
q

Sukhvir@Sukhvir-PC ~
$
于 2013-10-28T07:24:39.643 回答