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.
Asked
Active
Viewed 155 times
-1
Sander De Dycker
- 16,053
- 1
- 35
- 40
Sc3ron
- 21
-
Does this help: https://stackoverflow.com/questions/40038538/how-does-scanf-n-str-work-in-c-programming ? – Adrian Mole Dec 03 '19 at 12:24
-
3`"%*[^\n]"` can be used to clear the input stream until newline. Where `%*` is to ignore whatever read. – kiran Biradar Dec 03 '19 at 12:26
-
"in my understanding it just reads the input till \n and discards it then." And why couldn't that be a useful thing to do ? – Sander De Dycker Dec 03 '19 at 12:27
-
1@JL2210 it's not the same question. There is a * here, not in the question you referenced. – chmike Dec 03 '19 at 12:47
-
@chmike It's the same thing, the `*` only discards the input. – S.S. Anne Dec 03 '19 at 12:55
-
2@JL2210 : the question here is not so much *how* it works, but rather *why* you would use it. – Sander De Dycker Dec 03 '19 at 13:16
1 Answers
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