I used this lines to scan a string with space
scanf ("%*[^\n]", first_line);
printf("%s\n",first_line);
But it doesnt work!!! What to do?
I used this lines to scan a string with space
scanf ("%*[^\n]", first_line);
printf("%s\n",first_line);
But it doesnt work!!! What to do?
The *
in scanf ("%*[^\n]", first_line);
tells scanf
to scan but not store the scanned string.
In your case, you only have one argument, which is not set because of this.
Note that -Wall
(or -Wformat-extra-args
) issues a warning on "recent" gcc
compilers:
test.c: In function 'main':
test.c:6:8: warning: too many arguments for format [-Wformat-extra-args]
scanf ("%*[^\n]", first_line);
^~~~~~~~~
That works fine:
scanf ("%[^\n]", first_line);
printf("%s\n",first_line);
and you can even limit the size to read (making scanf
safer) like this:
char first_line[10] = {0};
scanf ("%9[^\n]", first_line);
so even if user enters more than 9 characters, you don't overflow your buffer
Note however that if no characters are present on the line before the \n
, scanf()
will fail to match the %[^\n]
conversion specification and return 0
without consuming any byte from standard input. For this reason, it is much more advisable to use fgets()
for your purpose:
char line[100];
if (fgets(line, sizeof line, stdin)) {
/* a line was read from standard input */
/* you can strip the newline character with this simple one liner */
line[strcspn(line, "\n")] = '\0';
printf("%s\n", line);
}
scanf ("%*[^\n]", first_line);
This code will discard all the characters until \n
is encountered. So you are not storing any value in your first_line
variable.
Don't use scanf
for reading character array or strings. Instead you can use fgets
.
char first_line[80];
while(fgets(first_line, 80, stdin)) {
printf("%s",first_line);
}
Where 80 is size of your first_line
character array.