%s
conversion specifier in the format string means scanf
reads a string from the stdin
buffer. Reading stops when a whitespace character is encountered and a terminating null byte is added to the buffer before scanf
returns. This means when you enter
"Hello Wolrd
^ space here
scanf
only read Hello
and returns. The corresponding argument to scanf
should be a pointer to the buffer, i.e., of type char *
, which stores the string and must be large enough to contain the input string else scanf
will overrun the buffer invoking undefined behaviour. However &test1
has type char (*)[25]
, i.e., a pointer to an array of 25
characters. What you need is
int main(void) {
char test1[25];
printf("Enter a string:\n");
scanf("%24[^\n]", test1);
printf("%s\n",test1);
return 0;
}
%24[^\n]
in the format string of scanf
means that scanf
will read an input string of length at most 24 and the string should not contain a newline. If either condition fails, scanf
will return. One character space should be save for the terminating null byte added by scanf
. Therefore we have 24
instead of 25
in the format string.
Alternatively, you can use fgets
to read a line from a stream. The scanf
call above can be replaced by
char test1[25];
fgets(test1, sizeof test1, stdin);
fgets
reads at most one less than sizeof test1
characters from stdin
(saves one character space for the terminating null byte) or till it reads a newline - whichever occurs first. If it reads a newline, it is stored in the buffer test1
.