c - 有没有办法将 scanf 与 "if"和 "else"语句一起使用?

标签 c scanf

我必须从 main 创建并调用一个函数。然后我必须调用 scanf 来读取两个整数并打印出较大的一个。然后我必须执行另一个 scanf,但这次使用 double 而不是整数。

int main()
{
   int x, y;
   scanf("%d%d", &x, &y);

   if (x > y)
   {
      printf("%d", x);
   }

   scanf("%lf%lf", &w, &z);

   if ( w > z)
   {
      printf("%f", w);
   }

   return 0;
}

我不确定我这样做是否正确,我将如何检查返回值以查看 scanf 是否有效?谢谢。

最佳答案

how would I check the return value to see that the scanf worked? 

通过检查scanf()的返回值。

  if( scanf("%d%d", &x, &y) != 2) 
  {
   /* input error */ 
  }

   if (x > y)
   {
      printf("%d", x);
   }

   if(scanf("%lf%lf", &w, &z) != 2) 
   { 
   /* input error */
   }

   if ( w > z)
   {
      printf("%f", w);
   }

来自 scanf()文档:

   These functions return the number of input items successfully matched
   and assigned, which can be fewer than provided for, or even zero in
   the event of an early matching failure.

   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure occurs.
   EOF is also returned if a read error occurs, in which case the error
   indicator for the stream (see ferror(3)) is set, and errno is set
   indicate the error.

关于c - 有没有办法将 scanf 与 "if"和 "else"语句一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16685301/

相关文章:

c - C 中的 fscanf csv。未分配值

c - 打开文件太多 : File IO in C on Windows

c - Scanf 在 C 中跳过每隔一个 while 循环

c - 在 C 中显示 float

c++ - 无法在 OpenSSL 中设置公钥/私钥

c - 使用 C 将逗号分隔的文本文件数据扫描到数组中

c - scanf 在 C 中不是很宽容

c - 双链表。我做的好吗?

c - 在 C 中将两个 8 位寄存器读入 ADXL362 的 12 位值

python - 如何通过添加自定义部分和符号来编辑 ELF