簡體   English   中英

輸入為空時如何停止掃描(掃描未知數的整數)

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

我目前正在開發一個程序,該程序掃描每個int並找出其是否完美。 問題是,我不知道輸入中有多少個整數,因此我想找出如何在輸入結束時停止掃描。

碼:

#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]);
  }
}

在這種情況下,我需要輸入500個數字才能運行代碼。 當輸入為空時,我需要它運行。 我知道有“ / 0”之類的東西,但我不知道如何在此代碼中使用它。

使用函數時,請閱讀文檔

回報價值

這些函數返回成功匹配和分配的輸入項的數量,該數量可能少於所提供的數量,在早期匹配失敗的情況下甚至為零。

因此,您需要檢查scanf的返回值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM