简体   繁体   中英

how can I ignore scanf() at certain characters?

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!

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.

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