简体   繁体   English

输入为空时如何停止扫描(扫描未知数的整数)

[英]how to stop scanning when input is null (scan an unknown number of ints)

I'm currently working on a program that scans each int and finds out if it is perfect or not. 我目前正在开发一个程序,该程序扫描每个int并找出其是否完美。 The problem is, I do not know how many ints there are in the input, so I want to find out how to stop scanning when the input ends. 问题是,我不知道输入中有多少个整数,因此我想找出如何在输入结束时停止扫描。

Code: 码:

#include <stdio.h>

int main() {
  int input[500], count;
  for (count = 0; count < 500; count++) {
    scanf("%d", &input[count]);
    if (input[count] == 0)
      break;
  }

  for (count = 0; count < 500; count++) {
    if (findFactors(input[count]) % input[count] == 0)
      printf("%d perfect\n", input[count]);

    else if (findFactors(input[count]) % input[count] <= 2 ||
             findFactors(input[count]) % input[count] >= input[count] - 2)
      printf("%d almost perfect\n", input[count]);

    else
      printf("%d not perfect\n", input[count]);
  }
}

In this case, I need to enter 500 numbers for the code to run. 在这种情况下,我需要输入500个数字才能运行代码。 I need it to run when the input is null. 当输入为空时,我需要它运行。 I know there is '/0' or something but I don't know how to use it in this code. 我知道有“ / 0”之类的东西,但我不知道如何在此代码中使用它。

When you use a function read the doc 使用函数时,请阅读文档

In return value 回报价值

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. 这些函数返回成功匹配和分配的输入项的数量,该数量可能少于所提供的数量,在早期匹配失败的情况下甚至为零。

So you need to check the return value of scanf: 因此,您需要检查scanf的返回值:

if (scanf("%d", &input[count]) != 1)
  break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM