Instead, of scanf("%c", &read)
you may consider read = getc(stdin)
.
Please, be aware that getc()
/fgetc()
return int
.
This allows to store any character as number in range [0, 255] as well as to return EOF
(usually -1) in case of failure.
So, with getc()
it would look like:
int read;
while ((read = getc(stdin)) != EOF)
Note:
You may assign read
to a variable of type char
– it will be implicitly converted. In case of getc()
succeeded, there shouldn't be any data loss in this implicit conversion.
A little sample to show this at work:
#include <stdio.h>
int main(void)
{
enum { N = 10 };
char buffer[N];
/* read characters and print if buffer ful */
int read, n = 0;
while ((read = getc(stdin)) != EOF) {
if (n == N) {
printf("%.*s", N, buffer); n = 0;
}
buffer[n++] = read;
}
/* print rest if buffer not empty */
if (n > 0) printf("%.*s", n, buffer);
/* done */
return 0;
}
Note:
The read characters are stored in buffer
without a termination ''
. This is handled in printf()
respectively by the formatter %.*s
meaning string with max. width *
where width and string are read as consecutive arguments.
Live Demo on ideone
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…