使用scanf检查输入是否为double?

时间:2013-12-02 07:48:31

标签: c

我正在从stdin读取输入并将数字存储到数组中。如果发生这种情况,我必须退出此读取过程:文件结束,scanf无法识别任何无效输入,或者阵列已满。

因此,对于“scanf无法识别的任何无效输入”,我想检查输入是否为double,如果不是,则退出for循环。有人可以解释如何做到这一点?我已经阅读了scanf的手册页,但我仍然不太了解它。

int reading;
double array[1000];

for(int i = 0; i < 1000; i++) {
      reading = scanf("%d", &array[i]);
      if (reading == EOF) {
         break;
      }
}

1 个答案:

答案 0 :(得分:1)

使用正确的转化并检查scanf()结果

int reading = scanf("%lf", &array[i]);
// If there is no input ...  (stdin is closed or I/O error, rare but possible)
if (reading == EOF) {
  break;
}
// Some input was available, but did not make sense for a double.
else if (reading == 0) {
  // The data is still in the input buffer and needs to be read before trying to read a double again.
  break;
}
// Input is good
else if (reading == 1) {
  break;
}
// Should never get here
else {
  break;
}

对于强大的I / O,我建议使用fgets()/ sscanf()代替。

char buffer[40];
if (fgets(buffer, sizeof buffer, stdin) == NULL) handle_EOF_or_IO_Error();
if (sscanf(buffer, "%lf", &array[i]) != 1) handle_unexpected_text_error();