c - 检查数组中是否存在数字的程序

标签 c arrays scanf

我编写了下面的 C 代码来检查一个数字是否存在于其元素由用户输入的数组中。但奇怪的是它跳过了第三个 printf语句,直接取输入打印Enter the number you wish to look for接受该输入后。这是什么原因造成的?在代码下方包含输入和输出框。

代码:

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

  void main() {
    int arr[30], size, i, num, flag=0;

    printf("Enter size of array. \n");
    scanf("%d",&size);

    printf("Enter %d array elements one by one. \n",size);
    for (i=0; i<size; i++) {
        scanf("%d \n",&arr[i]);
    }

    printf("Enter the number you wish to look for. \n");
    scanf("%d",&num);

    for(i=0;i<size;i++) {
        if (num == arr[i]) {
            flag++;
        }
    }

    if (flag>0) {
        printf("The number %d is present in the array.",num);
    } else {
        printf("The number %d is not present in the array.",num);
    }
 }

输入/输出:
Enter size of array.
5
Enter 5 array elements one by one.
1
2
3
4
5
5
Enter the number you wish to look for.
The number 5 is present in the array.

你可以看到 Enter the number you wish to look for.应该在 5 之前,但事实并非如此。

已解决

只需移除 \n 即可修复来自 scanf .

最佳答案

scanf , 空格字符已经表示任何空格。所以在您的 "%d \n"该函数已经在最后一位数字之后处理了新行,但随后您强制它等待另一个换行符。

这会导致程序等待另一行。输入后,程序继续并要求搜索号码,此时输入已经输入。

只使用 scanf 中的一个空格,它已经适用于换行符,最好在数字本身之前,这样您就不需要额外的一行来完成操作:

scanf(" %d", arr + i);

关于c - 检查数组中是否存在数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040710/

相关文章:

c - 读取Linux内核空间中的字符设备

arrays - Perl:一次从多个数组中进行grep

C - 在外部函数的指针数组中分配值

c - 总线错误 10,结构内有二维结构数组

javascript - 多维数组。推送然后加入

c - scanf ("%[^\n]s",a) 与 gets(a)

c - scanf() 格式字符串中尾随空格有何影响?

c++ - uint8_t、uint16_t、...的格式说明符?

android - Android 平板电脑上的 C/C++ 应用程序

c - 循环直到用户输入一个整数,但如果终端上不存在整数则跳过读入