ajay
ajay

Reputation: 9680

scanf doesn't put a terminating null byte

I am reading a string from stdin using the scanf function.

char inputWord[100];
scanf("%99[^\n]", inputWord);

This works fine except the case when the first character in the input sequence is a newline (entered by pressing the enter key). When I print the length of inputWord using strlen, it prints 6 (always) and when I print the inputWord string itself, it prints some garbage. man page of scanf states that a terminating null byte is added after the first match of a character in the input sequence with the set of excluded characters which here is [^\n]. Why is it not adding a null byte in this case? Is it because scanf cannot match any character in this case (return value is zero)?

I know I should be using fgets but I am just curious to know the behaviour of scanf in this case. Seems like scanf is one beast of a function.

Upvotes: 1

Views: 3492

Answers (1)

Michael Burr
Michael Burr

Reputation: 340198

The return code from scanf() in that case will be 0 since it didn't match anything for the conversion spec (and since nothing matched for the conversion spec, nothign is written to the corresponding variable).

Upvotes: 4

Related Questions