hageApple
hageApple

Reputation: 11

Why does printf prints only first character of a character array whose input was read through scanf

This code is supposed to read input string through scanf and store the input string in an array declared here as msg[] and then print those input string, but when I run the code all it prints is just the first character of the string. It looks really simple but I am not able to solve it.

If I type i do, it only reports i.

#include <stdio.h>

int main()
{
    char msg[5]; 
    printf("enter the message: ");
    scanf("%s",msg);           
    printf("entered msg is: %s", msg); 
}

Upvotes: 0

Views: 2011

Answers (2)

John Bode
John Bode

Reputation: 123488

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 ); 

Upvotes: 0

KevinDTimm
KevinDTimm

Reputation: 14376

The answer is hidden in the comments. The OP states if i give input "i do" it prints only 'i' .

scanf only reads until the first whitespace (which is the i in i do).

If you input 4 characters, 4 characters are printed.

Please edit your question to include this information for future searchers.

Upvotes: 4

Related Questions