Simon said:
Why not
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]%*c", array);
Thank you.
I don't know how to make that line work in a loop.
A subsequent call to fscanf, returns 0.
/* BEGIN pops_device.c */
/*
** If rc equals 0, then an empty line was entered
** and the array contains garbage values.
** If rc equals EOF, then the end of file was reached,
** or there is some input problem.
** If rc equals 1, then there is a string in array.
** Up to LENGTH number of characters are read
** from a line of a text stream.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>
#define OLD_WAY 1
#define LENGTH 50
#define str(x) # x
#define xstr(x) str(x)
int main(void)
{
int rc;
char array[LENGTH + 1];
puts("OLD_WAY is " xstr(OLD_WAY));
puts("The LENGTH macro is " xstr(LENGTH));
fputs("Enter a line with spaces:", stdout);
fflush(stdout);
#if OLD_WAY != 0
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
#else
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]%*c", array);
#endif
if (1 > rc) {
*array = '\0';
}
printf("rc is %d. Your string is:%s\n\n", rc, array);
while (rc == 1) {
fputs("Hit the Enter key to end,\nor enter "
"another line to continue:", stdout);
fflush(stdout);
#if OLD_WAY != 0
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
#else
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]%*c", array);
#endif
if (1 > rc) {
*array = '\0';
}
printf("rc is %d. Your string is:%s\n\n", rc, array);
}
return 0;
}
/* END pops_device.c */