Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

c - Why does comparing the result of scanf() with NULL generate a compiler warning?

I'm writing in C and I need to read everything that arrives in input but I don't know how many characters I will receive. I wrote

while (scanf("%c", &read) != NULL)

but the compiler tells me: [Warning] comparison between pointer and integer, so what should I write instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...