Hi everyone

I have a simple piece of code thus:

char userChoice = '\0';

validate:;

printf("Please make a choice [y/n] \n"); //fflush (stdout) ;
scanf("%c", &userChoice);

if(userChoice != 'y' && userChoice != 'n' )
{
    printf("\nInvalid input; please enter y or n. \n ");
    userChoice = '\0';
    goto validate;
}

 printf("\n %c was your choice. \n ", userChoice ); fflush (stdout) ;

It is working, but the problem I have is that when the goto executes, it seems to do so twice:

Please make a choice [y/n]
j

Invalid input; please enter y or n.
 Please make a choice [y/n]

Invalid input; please enter y or n.
 Please make a choice [y/n]
n

 n was your choice.

I suspect there is something really simple here that I am missing.

Thanks

Recommended Answers

All 4 Replies

You should avoid goto completely. After 30 years in C, I've never needed one.

Restructure your program to use one of the 3 loop structures.

As for why it executes twice, when you type your answer, how many keys do you actually press? What do you think is now happening?

[edit]
One more thing:
Why use an expensive function like scanf() to read a single character? getchar() is specifically designed to read a character without all the overhead.

It won't solve your double-execute problem, though...
[/edit]

I managed to get around this - having read several posts in the meantime which told me goto statements are pure evil, I managed to find a simple alternative here:

http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_032.htm

If you can't be bothered to go there, then here's the code:

/* example one, a simple continue statement */
#include <stdio.h>
#include <ctype.h>

main()
{
    int     valid_input;    /* when 1, data is valid and loop is exited */
    char    user_input;     /* handles user input, single character menu choice */

    valid_input = 0;
    while( valid_input == 0 ) {
        printf("Continue (Y/N)?\n");
        scanf("  %c", &user_input );
        user_input = toupper( user_input );
        if((user_input == 'Y') || (user_input == 'N') )  valid_input = 1;
        else  printf("\007Error: Invalid choice\n");
    }
}


    Sample Program Output
    Continue (Y/N)?
    b
    Error: Invalid Choice
    Continue (Y/N)?
    N

Thanks for taking the time to reply WaltP.

I had not considered the carriage return key.

All sewn up rather neatly - you pointed out why my original problem was occuring, and a more efficient (at least - one without a goto) solution was put forward.

Too complicated. You can do this much cleaner and without the valid_input variable.

And just for future user info, if anyone puts a \007 in any output statements I have to use, someone's going to get strangled. It's an annoying practice from the user's standpoint.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.