打印功能不允许输入第一个值

时间:2017-12-01 04:59:23

标签: c printf

我在运行代码时无法从键盘输入值。一切都成功编译,但当我运行我的代码时,它会打印出来:

How many numbers would you like to place in the array: 7
Enter number 1: Enter number 2: 

等等

为什么会这样?另外,有没有办法计算和存储每个元素在数组中的次数?

int main(void)
{

    int numbers = 0;
    int j = 0;
    char numStorage[j];
    int times = 0;
    char newArray[j];

    printf("How many numbers would you like to place in the array: ");
    scanf("%d", &numbers);

    j = numbers;

    int i = 1;

    while (i < (numbers + 1))
    {
        printf("Enter number %d: ", i);
        scanf("%c", &numStorage[i]);
        i++;
    }//close of while loop

    int x;

    for (x = 0; x < numbers; x++)
    {
        newArray[x] = numStorage[x];
    }//close of for loop

    int z;
    int q;

    for (z = 0; z < numbers; z++)
    {
        for (q = 0; q < numbers; q++)
        {
            if (numStorage[z] == numStorage[q])
            {
                times++;
                q++;
            }//close of if
            else
            {
                q++;
            }//close of else
        }//close of for loop

        printf("\n%d occurs %d times", numStorage[z], times);
        z++;
        q = 0;
        times = 0;
    }//close of for loop

}//end of main method

1 个答案:

答案 0 :(得分:2)

int j = 0;
char numStorage[j];

您将numStorage声明为零元素的字符数组。

然后,在

int i=1;
while (i < (numbers + 1))
    {
        printf("Enter number %d: ", i);
        scanf("%c", &numStorage[i]);
        ..
     }

您正在尝试将字符分配给明确超出限制访问权限的numStorage[1]

应该是

 j = numbers;
 char numStorage[j];
 ...
 int i=0;
  while (i < numbers) # Array indices should be 0 to numbers-1

修改

在您刚读取数字后再次使用scanf读取字符(再次使用scanf)也是一个问题,您应该检查[ this ]问题以获得解决方法。