Christian Anderson
Christian Anderson

Reputation: 1

Why does scanf() stop working after the terminator character for %s in the following excerpt?

#include <stdio.h>

using namespace std;

int main(void)
{
    int length, width;
    char str[3];
    // buffer size will be handled later
    scanf("/length{{%d}{%[^}]s}{%d}}", &length, str, &width);
    printf("%d %s %d", length, str, width); 
    return 0;
}

Please note: I don't work with C/C++ that often. Any help will be appreciated. The I/O for me personally using GCC and MSVC is:

# INPUT
/length{{5}{mm}{5}}

#OUTPUT
5 mm -400240432

Upvotes: 0

Views: 46

Answers (1)

William Pursell
William Pursell

Reputation: 212434

The input string /length{{5}{mm}{5}} does not contain a literal s, so the format string "/length{{%d}{%[^}]s}{%d}}" cannot match. You want to drop the s in the format string and use "/length{{%d}{%2[^}]}{%d}}". Note the width modifier on the [ conversion specifier.

This is a common error. The %[ portion of the format string is not some kind of modifier for the %s conversion specifier, but is its own conversion specifier. When you write %[...]s, the conversion specifier ends at ] and the s is treated as a literal character to be matched.

Upvotes: 4

Related Questions