简体   繁体   中英

How to ignore all inputs after first character with scanf in loop?

I'm asking user to input character, but the problem is that if user inputs multiple characters, the loop will be executed for all characters.

    do
    {
        printf("For input type 'u', for output type 'p': ");
        scanf("%c", &c); 
    } while ((c != 'u') && (c != 'p'));

So if user for example types 'aaaa' , loop will be executed 5 times with repeated printf text. I tried getchar(); after scanf , using conversion string " %c" , "%c%*c but nothing worked. Is there a way to execute loop for only first character?

Do you want to print the statement only one time in case the character is other than u/p. if it is yes, you can move the print statement above the do loop or use the condition statement by checking c value is set or not. It will print the statement only once. My syntax may be incorrect, check the c programming guide.

1. 
    printf("");
       do{
         }while

2.     do{
               if(c != '\0')
               {
                printf("For input type 'u', for output type 'p':");
               }
            scanf('%c',&c);
           } while ((c != 'u') && (c != 'p'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM