我想从终端读取一些数字并随后打印它们。 然而,它们似乎都是某种随机值,而不是我提供的值。
为什么我的输入没有正确保存?
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/