c - 为什么我在这个简单的程序中得到随机垃圾值?

标签 c

我想从终端读取一些数字并随后打印它们。 然而,它们似乎都是某种随机值,而不是我提供的值。

为什么我的输入没有正确保存?

int main (void)
{    
    int i = 0 , numeros[21] , cont = 1, z = 0;

    puts("\n === Bienvenido ===\n"); 
    puts("\n === Vamos a procesadar  un numero de serie de 20 digitos [Numericos] ===\n");  
    puts("\n === Dime los numeros ===\n"); 

    while (cont != 20 )
    {
        fflush(stdin);
        scanf("%d", &numeros[i]);      

        printf("\n === Dime otro numero. Numeros: %d ===\n", cont); 
        cont++;
    }
    for (z = 0; z < 20; z++)
    {
        printf("\nLos numeros son: %d\n", numeros[z]);
    }
    system("pause");
}

最佳答案

好的,有几个问题:

  • numeros 被声明为一个包含 21 个整数的数组,但您使用它时就好像它是 numeros[20]
  • 未定义的行为,因为您在 stdin 上调用 fflush
  • scanf("%d", &numeros[i]) 虽然不安全,但一切都很好,但 i 永远不会增加
  • 检查函数的返回值...总是:scanf 返回它扫描的值的数量,如果返回 0,则没有扫描 %d,并且 numeros[i] 需要重新分配。

这是我如何编写您的程序的示例:

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

int main ( void )
{
    int c,i=0,
        numbers[20],
        count=0;
    //puts adds new line
    puts("enter 20 numbers");
    while(count < 20)
    {
        c = scanf(" %d", &numbers[i]);//note the format: "<space>%d"
        if (c)
        {//c is 1 if a number was read
            ++i;//increment i,
            ++count;//and increment count
        }
        //clear stdin, any trailing chars should be ignored
        while ((c = getc(stdin)) != '\n' && c != EOF)
            ;
    }
    for (i=0;i<count;++i)
        printf("Number %d: %d\n", i+1, numbers[i]);
    return 0;
}

关于c - 为什么我在这个简单的程序中得到随机垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24950252/

相关文章:

C - 定积分求积法则

使用所有小数位的 union 将 char 数组转换为 double

C套接字原子非阻塞读取

c - 在 C 语言中, `fputc` 什么时候可以返回第一个参数以外的值?

c - 文件 I/O 未附加

c - 如何获取字符串中的第一个单词并将其转换为int

c - 使用 GCC 和 bool 指针的条件运算符的奇怪结果

c - 记录到屏幕和文件

C - 套接字编程 - 任意发送/接收 - 指针算术 - 数组不可分配

c++ - c++标准中有多少个头文件?