简体   繁体   中英

scanf formatted input does not apply to first character scanned

I'm trying to write a program that outputs non-vowel characters (without if statements and using formatted scanf input). The code I currently have does not apply the %*[] ignored characters to the first %c character scanned, but the restriction applies for the other characters. For example, "Andrew" becomes "Andrw" instead of "ndrw". I'm suspecting this could be due to the %c at the beginning. Could someone help me please? :)

#include <stdio.h>
#include <string.h>

int main(void) {
    char c;
    while (scanf("%c%*[aeiouAEIOU]", &c) == 1)
        printf("%c", c);
    return 0;
}

The scanf formats are matched in order so %c is matched first for the A . You need to use 2 separate scanfs for this, or precede the loop with the initial-vowel eating scanf:

scanf("%*[aeiouAEIOU]");
while (scanf("%c%*[aeiouAEIOU]", &c) == 1) { 
    printf("%c", c);
}

The question is is this any clearer and better than

int c;
while ((c = getchar()) != EOF) {
    if (! strchr("aeiouAEIOU", c)) {
        putchar(c);
    }
}

I have an opinionated answer...

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