Re: Discarding unread data after scanf()
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Sun, 25 Mar 2007 13:05:45 GMT
Army1987 wrote:
Is this a good way to discard unread data after scanf()?
A call to fscanf with stdin as the first argument,
is just like a call to scanf.
/* BEGIN fscanf_input.c */
/*
** There are only three different values
** that can be assigned to rc
** from the fscanf calls in this program.
** They are:
** EOF
** 0
** 1
** If rc equals EOF, then the end of file was reached,
** or there is some input problem;
** ferror and feof can be used to distinguish which.
** If rc equals 0, then an empty line was entered
** and the array contains garbage values.
** If rc equals 1, then there is a string in the array.
** Up to LENGTH number of characters are read
** from a line of a text stream
** and written to a string in an array.
** The newline character in the text line is replaced
** by a null character in the array.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>
#define LENGTH 40
#define str(x) # x
#define xstr(x) str(x)
int main(void)
{
int rc;
char array[LENGTH + 1];
puts("The LENGTH macro is " xstr(LENGTH) ".");
do {
fputs("Enter any line of text to continue,\n"
"or just hit the Enter key to quit:", stdout);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
if (rc == 0) {
array[0] = '\0';
}
if (rc == EOF) {
puts("rc equals EOF");
} else {
printf("rc is %d. Your string is:%s\n\n", rc, array);
}
} while (rc == 1);
return 0;
}
/* END fscanf_input.c */
--
pete
.
- Follow-Ups:
- Re: Discarding unread data after scanf()
- From: Army1987
- Re: Discarding unread data after scanf()
- References:
- Discarding unread data after scanf()
- From: Army1987
- Discarding unread data after scanf()
- Prev by Date: Re: Cross platform lib in 'C'
- Next by Date: Re: pointer type casting
- Previous by thread: Discarding unread data after scanf()
- Next by thread: Re: Discarding unread data after scanf()
- Index(es):
Relevant Pages
|
Loading