Pregunta

I tried to have defensive programming having input as an integer but the program would go into infinite loop if I entered a character. I then switched to having input as a character, but it does the loop twice. Once for the wrong character and once for the end of line keystroke.

Is there any way to get the loop, just once?

code:

int main(int argc, char *argv[])
{
    char choice='5';
    while (choice != '1' && choice !='2' && choice !='3' && choice!='4' && choice!='0')
        {
             printf("Parakalw epilekste ena apo ta parakatw\n\n");
             printf("1.\tKafe 1.5 euro\n");
             printf("2.\tKafe me gala 1.8 euro\n");
             printf("3.\tSokolata 2.1euro\n");
             printf("4.\tSokolata me gala 2.4 euro\n");
             printf("0.\tExodos\n\n");
             printf("parakalw eisagete thn epilogh sas: ");
             scanf("%c",&choice);
        }
system("PAUSE");    
return 0;
}
¿Fue útil?

Solución

Use scanf(" %c", &choice) to make it skip over whitespace, otherwise your linefeed is left in stdin after picking the character, and it will be read in the next scanf call. The space before the specifier means it will match any kind of whitespace character (spaces, tabs and returns).

Otros consejos

For defensive programming (what ever you mean by that exactly), I would not use scanf at all, it is so easy to make mistakes with it.

Instead, read input line with fgets, then parse that as needed, then use trimming, custom parsing code or possibly sscanf, probably after some validation.

Also, you'd better check return value of any *scanf function, always. Check both for actual error, and how many items were actually scanned.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top