从数组中输入多个数字,并检查每个数字是否为整数

3
大家好!希望有人能帮我解决C语言的问题。这是我在IT方面的第一个严肃作业,我没有经验,正在进行网络学习,所以老师的帮助不是很容易得到。
我需要开发一个C语言控制台应用程序。用户需要输入10个整数,如果插入的数字不是整数,则需要输出错误并重新输入新数字,直到所有10个整数都被插入。
如果我说这10个数字不能为0,那么一切都可以正常工作(我这样做是为了确保我的if-else语句有效),但是当我想要检查每个输入的数字是否为整数时,就无法正常工作。
我该如何正确地做呢?
目前我的代码看起来像这样:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    float f;
    int numbers[10];

    for (i = 0; i < 10; i++)
    {
        scanf ("%d", &numbers[i]);
        if (numbers[i] != 0)
        {
            scanf ("*%d", &numbers[i]);
        }
        else
        {
            printf ("\nError!Entered number is't integer \n");
            printf ("\nPlease insert number again \n");
            scanf("%*d", &numbers[i]);
        }

    }

}

1
请见:https://dev59.com/cmXWa4cB1Zd3GeqPLD4C - Lesto
5个回答

1
#include <stdio.h>

int main(void) {
    int i = 0;
    int val;
    char ch;
    int numbers[10];

    while(i < 10) {
        val = scanf("%d", numbers + i);  // read the integer into a[i]
        if(val != 1) {
            while((ch = getchar()) != '\n')  // discard the invalid input
                ;  // the null statement
            printf("Error! Entered number is not an integer.\n");
            printf("Please enter an integer again.\n");
            val = scanf("%d", numbers + i);
            continue;
        }
        ++i;
    }
    // process the numbers array
    return 0;
}

我再次写下这行代码

val = scanf("%d", numbers + i);

现在它按照我的需求工作。太棒了 - 非常感谢。

似乎应该删除第二个 val = scanf("%d", numbers + i); - chux - Reinstate Monica

0

你可以使用以下几种技术:

  1. 将数字读作字符串,如果包含不适合整数的字符,则拒绝。然后使用 sscanf() 将字符串转换为整数。

  2. 将数字读作浮点数,如果超出整数范围或具有非整数值,则拒绝。

  3. 逐个字符读取输入,并构建一个整数值。如果出现无效字符,则拒绝该值。


谢谢您的快速回复。 您能否为每个选项编写一个代码示例呢? 今天我已经尝试了sscanf,但是似乎有些地方出了问题。 - effeja

0

scanf 返回成功匹配和赋值的输入项数量。您可以检查每次调用 scanf 的此值是否为 1。如果该值为0,则应丢弃输入以清除 stdin 缓冲区并重新读取输入。

#include <stdio.h>
#include <ctype.h>

int main(void) {
    int i = 0; 
    int val;
    char ch;
    int numbers[10];

    while(i < 10) {
        // read an integer and the first non-numeric character

        val = scanf("%d%c", numbers + i, &ch);  

        // if the number of items assigned by scanf is not 2 or if 
        // the first non-numeric character is not a whitespace, then
        // discard the input and call read input again.
        // for example input of type 32ws are completely discarded

        if(val != 2 || !isspace(ch)) {
            while((ch = getchar()) != '\n')  // discard the invalid input
                ;  // the null statement
            printf("Error! Entered number is not an integer.\n");
            printf("Please enter an integer again.\n");
            continue;
        }
        ++i;
    }
    // process the numbers array
    return 0;
}

谢谢。这个程序可以运行,但是有没有办法在数组中排除非整数的数字。例如,用户输入1 2 3 0.5(错误)4(代替0.5)5 6 7 8 9 10 = 总共输入了10个数字(整数),因为在你的代码中他不会让最后一个数字进入,因为他计算出那里有一个不是整数的数字。 - effeja
@effeja 那么你最好的选择是将整数读取为字符串,然后检查该字符串是否包含任何非数字字符。 - ajay
@effeja请查看更新后的答案,现在它已经实现了您想要的功能。 - ajay

0

虽然我并不完全清楚你问题的细节,但是这里提供了一个与你所需相似的代码示例:

int main(void)
{
    int i;
    int numbers[10];
    int sum = 0;

    for(i=0; i<10; ++i)
    {
        printf("Enter #%d:\n", i+1);
        scanf("%d", numbers+i);

        if (numbers[i] % 2 == 0) // Then Number is even
        {
            sum += numbers[i];
        }
    }

    printf("The sum of only the even numbers is %d\n", sum);

    getch();
    return 0;
}

0

如果要读取一个 int,建议使用 fgets() 然后使用 sscanf()strtol()

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int i;
  int numbers[10];

  for (i = 0; i < 10; ) {
    char buffer[50];
    if (fgets(buffer, sizeof buffer, stdin) == NULL) break; 
    int n;  // number of `char` parsed
    if (sscanf(buffer, "%d %n", &numbers[i], &n) != 1 || buffer[n] != '\0') {
      printf("Error! Entered number is not an integer.\n");
      printf("Please enter an integer again.\n");
      continue;
    }
    i++;
  }
  return 0;
}

使用 strtol() 方法。它可以检测溢出问题:

    if (fgets(buffer, sizeof buffer, stdin) == NULL) break; 
    char *endptr;
    errno = 0;  
    long num = strtol(buffer, &endptr, 10);
    if (errno || num < INT_MIN || num > INT_MAX) Handle_RangeError();
    if (buffer == endptr || *endptr != '\n') Handle_SyntaxError();
    numbers[i] = (int) num;        

推荐创建一个可以重复使用的函数int GetInt(const char *prompt)
用户输入是不可信的。在经过充分审查之前,请勿相信它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接