Home > database >  how can I ignore scanf() at certain characters?
how can I ignore scanf() at certain characters?

Time:09-28

Is it possible to ignore scanf() in a while loop if a certain character was scanned?

For example:

int i = 0;
char b = 32;

while (scanf("%c", &b) == 1) {
    if (b == '\n') {
        printf("r");
    } 
    i  ;  
}

output after pressing enter: "r". output after pressing whitespace enter: "r". But here I expect no output! I want the output only when an enter is pressed and nothing before!

CodePudding user response:

You can use a flag to indicate whether there have been other characters before the newline. Something like:

char b = 32;
int flag = 1;

while (scanf("%c", &b) == 1) 
{
    if (b == 'q') break;  // End program when q is pressed

    if (b == '\n') 
    {
        // Only print if the flag is still 1
        if (flag == 1)
        {
            printf("r");
        }

        // Set the flag to 1 as a newline starts
        flag = 1;
    }
    else
    {
        // Other characters found, set flag to 0
        flag = 0;
    }
}

For input like

\n   // newline will print an r
 \n  // space   newline will not print anything
a\n  // a   newline will not print anything

In general this code will only print when input is a newline without any preceeding characters.

  • Related