0

Explain the bug

Assuming user enters "hello world"output is hello 0

1st Apr 2020, 9:23 PM
Ajith
Ajith - avatar
4 Réponses
+ 3
In this case scanf reads 2 inputs, a string (%s) and an int (%d). "hello world" are 2 inputs because of the space, you basically provide it with 2 %s. When scanf reads the 2nd input, "world" it expects it to be an int, yet it encounters an invalid character, 'w', so it just aborts. The final value can be anything because it's undefined behavior.
1st Apr 2020, 10:18 PM
Dennis
Dennis - avatar
0
char str[100]; int i; scanf("%s %d",str,&i); printf("%s %d",str,i);
1st Apr 2020, 9:24 PM
Ajith
Ajith - avatar
0
(Silly me - I for some reason saw two printf statements.)
1st Apr 2020, 10:20 PM
HonFu
HonFu - avatar
0
Thanks
2nd Apr 2020, 11:03 AM
Ajith
Ajith - avatar