qu4lizz
qu4lizz

Reputation: 359

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?

Upvotes: 0

Views: 209

Answers (1)

srinivasa rao
srinivasa rao

Reputation: 23

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'));

Upvotes: 1

Related Questions