-1

I have an assignment where i need to find out what scanf("%*[^\n]"); does in a c program. I know that [^\n] means that the input is read until \n and that %* puts the input in the buffer and discards it. I don't understand what usage you can get out of it, because in my understanding it just reads the input till \n and discards it then.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
Sc3ron
  • 21

1 Answers1

1

scanf(“%*[^\n]”); usage in a c programm?

It is somewhat common to see yet fgets() is a better approach. Recommend to not use scanf() until you know why you should not use it. Then use it in a limited way.


I don't understand what usage you can get out of it

Example usage: code attempts to read numeric text with scanf("%d", &x); but "abc\n" is in stdin so function returns 0 and data in stdin remains. scanf("%*[^\n]"); clears out (reads and discards) the "abc" in preparation for a new line of input.

int x;
int count;
do {
  puts("Enter number");
  count = scanf("%d", &x);  // count is 0, 1 or EOF
  if (count == 0) {
    scanf("%*[^\n]");   // Read and discard input up, but not including, a \n
    scanf("%*1[\n]");   // Read and discard one \n
  }
} while (count == 0);

if (count == EOF) puts("No more input");
else puts("Success");

Variations like scanf(" %*[^\n]"); and scanf("%*[^\n]%*c"); have their own corner problems (1st consume all leading white-space, even multiple lines, 2nd fails to read anything if the next character is '\n').

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256