Kaiyaha
Kaiyaha

Reputation: 480

Is there a way to make space input obligatory in the scanf() function?

For example, I want to make a user type a required message before values, like this:

scanf(" Message%c", &character);

That's fine, but then I want this message to contain some spaces like this:

scanf(" A required message %c", &character);

The compiler does not complain about anything, but the spaces do not matter, the input:

A required message C

and

ArequiredmessageC

give the same result.

Is there a way to make these spaces mandatory?

Upvotes: 3

Views: 153

Answers (2)

chqrlie
chqrlie

Reputation: 144715

You can use the %[ conversion specifier with a 1 length modifier and a * to suppress assignment:

if (scanf("%*1[ ]A%*1[ ]required%*1[ ]message%*1[ ]%c", &character) == 1) {
    // Input is conforming, last character is in `character`
} else {
    // Input is not as expected...
    // but there is no way to tell how many characters were correct
}

This is very cumbersome and hard to read. You could use fgets() as an alternative:

char buf[80];
if (fgets(buf, sizeof buf, stdin) {
    const char *prefix = " A required message ";
    size_t len = strlen(prefix);
    if (!memcmp(buf, prefix, len)) {
        char c = buf[len];
        // handle correct message
    } else {
        printf("Invalid input: %s", buf);
    }
} else {
    printf("Unexpected end of file\n");
}

Upvotes: 8

KamilCuk
KamilCuk

Reputation: 140970

You can explicitly match one space:

scanf("%*1[ ]A%*1[ ]required%*1[ ]message%*1[ ]%c", &character);

Upvotes: 4

Related Questions