Weicheng Xing
Weicheng Xing

Reputation: 33

How does scanf("%[^:]]", word) working in C

scanf("%[^:]]", word)

I know the command tries to scan user input until ":" is detected, but I am not sure about what does the last "]" in the front part do.

Upvotes: 1

Views: 50

Answers (1)

chux
chux

Reputation: 153348

what does the last "]" in the front format part do?

Nothing useful.

Usually a lone "]" will scan in a matching ]. If one is found. it is read from stdin and thrown away. Else scanning stops.

Yet since it follows "%[^:]", which continues scanning in data until a ':' is encountered1, a following "]" will not occur.


The following makes more sense:

// Limit input, scan in non-`:` and then and scan in an excluded ':'.
char word[100];
if (scanf("%99[^:]:", word) == 1) Success();

1 Scanning continues until a ':' is the next character, or end-of-file is signaled or input error occurs.

Upvotes: 3

Related Questions