The %s
conversion specifier tells scanf
to skip over any leading whitespace, then read up to (but not including) the next whitespace character. So when you enter "i do"
, the %s
conversion specifier only reads "i"
.
If you want to read strings with whitespace, you'll have to use a different method. You can use the %[
conversion specifier like so:
scanf( "%[^\n]", msg );
which will read everything (including leading whitespace characters) until it sees the '\n'
newline character and stores it to msg
. Unfortunately, this (and the %s
specifier above) leave you open to buffer overflow - if your user enters a string longer than msg
is sized to hold, scanf
will happily write those extra characters to the memory following the msg
buffer, leading to all kinds of mayhem. To prevent that, you'd use a field width in the conversion spec, like so:
scanf( "%4[^\n]", msg );
This tells scanf
to read no more than 4 characters into msg
. Unfortunately, that width has to be hardcoded - you can't pass it as an argument the way you can with printf
.
IMO, a better way to go would be to use fgets
:
fgets( msg, sizeof msg, stdin );