0

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?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Tonmoy Mohajan
  • 91
  • 2
  • 4
  • 13

2 Answers2

5

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);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2
 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.

Disadvantages of scanf

char first_line[80];
while(fgets(first_line, 80, stdin)) {
    printf("%s",first_line);
}

Where 80 is size of your first_line character array.

ani627
  • 5,578
  • 8
  • 39
  • 45
  • Dear downvoter I would really appreciate if you could provide a reason for the downvote. This way I can improve my post and learn something new. Thanks! – ani627 May 03 '17 at 20:12
  • not the downvoter, but you didn't explain why the OP code didn't work, and just proposed another way to do it, discouraging him/her to use `scanf`, which is still useful when used properly. It gives the impression of an off-topic answer. Then, (this is probably minor) `fgets` isn't strictly equivalent since it consumes the \n – Jean-François Fabre May 03 '17 at 20:33
  • Thanks for the input @Jean-FrançoisFabre. – ani627 May 03 '17 at 20:50
  • at least you improved your post. +1 – Jean-François Fabre May 03 '17 at 20:59