Reputation: 77
i wrote a program for sorting the names of persons and i ask the user to give the number of persons that he want, and i stored it by using the below given line and it worked properly but, i din't understand the exact working of it. Can anyone explain it clearly?
scanf("%d%*c",&n);
Upvotes: 2
Views: 4065
Reputation: 153348
%*c
consumes the first char
after the number (if there was one), be it a '\n'
, some other white-space, alpha, anything including '\0'
.
The '*'
in %*c
, directs scanf()
to consume, but not save that char
.
If no number was scanned via "%d"
, maybe due to invalid input, then "%*c"
does nothing as the preceding directive failed and "%*c"
is not evaluated.
Using scanf("%d%*c",&n);
has weak error handling. For robust code, use a helper function. Needless to say, this is far more complicated, but unfortunately C does not provide simple and robust reading of even simple things like int
.
// Read 1 line, decode an `int`, save in *n
// Return EOF, 0:Invalid, 1:Success
int ReadInt(int *n) {
int i;
char buf[50];
if (fgets(buf, sizeof buf, stdin) == NULL) {
return EOF; // EOF occurred
}
char *endptr;
errno = 0;
long num = strtol(buf, &endptr, 10);
if (buf == endptr || (*endptr != '\n' && *endptr != '\0')) {
return 0; // failed conversion
}
if (errno || num < INT_MIN || num > INT_MAX) {
return 0; // range error
}
if (n != NULL) {
*n = (int) num;
}
return 1;
}
Even this could be expanded to get for excessively long lines.
Upvotes: 0
Reputation: 19864
%*c
is used to ignore the newline space or any other special characters.
So in this scanf()
after entering the integer let's say you have a newline character in the buffer which will be gobbled by this %*c
.
If you are not doing this and just after this scanf() if you have say
scanf("%c",&c); /* where c is a char */
Then you will be wondering that scanf() will never wait for you to enter a character instead it picks a newline character.
Upvotes: 5
Reputation: 18299
From here: scanf format string
"An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable."
Upvotes: 0