为什么程序没有等待用户输入就退出了?

Why does the program exit, without waiting for the user input?

此 C 程序应该根据用户输入的元素数量分配内存并将它们相加并打印结果。它再次提示用户是否要添加更多号码。但是在输入 Y/N 时,控制台关闭并且程序意外结束。如何解决这个问题?

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

int main()
{
    int n,i;
    int *ptr,*old_ptr;
    int sum = 0;
    char a;

    printf("Enter the number of elements to be added: ");
    scanf("%d",&n);

    ptr = calloc(n,sizeof(int));
    ptr = old_ptr;

    printf("Enter the elements:\n");

    for(i = 0;i < n;i++){
        scanf("%d",ptr);
        sum = sum + *ptr;
        ptr++;
    }
    printf("The sum total of the numbers is: %d\n\n\n",sum);

    printf("Do you want to enter more numbers ?\nPress Y/N: ");
    scanf("%c",&a);
    if(a == 'Y'){
        printf("\n\nYou have entered: %c\n\n",a);
        ptr = realloc(old_ptr,sizeof(int)*n);

        printf("Enter the elements:\n");

    for(i = 0;i < n;i++){
        scanf("%d",&ptr);
        sum = sum + *ptr;
        ptr++;
    }
    printf("The total of the numbers is: %d\n\n\n",sum);
    }
    if(a == 'N'){
        printf("Program finished!");
    }
    return 0;
}

请查看修改后的代码。

scanf("%c",&a);

问题:scanf 从输入缓冲区读取 \n (ASCII:10),并且没有进一步等待用户输入。 a 中存储的值将为 10 (\n)。由于 a 不等于 "Y' 或 'N',程序退出。

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

int main()
{
    int n,i;
    int *ptr,*old_ptr;
    int sum = 0;
    char a;

    printf("Enter the number of elements to be added: ");
    scanf("%d",&n);

    ptr = calloc(n,sizeof(int));
    old_ptr=ptr;

    printf("Enter the elements:\n");

    for(i = 0;i < n;i++){
        scanf("%d",ptr);
        sum = sum + *ptr;
        ptr++;
    }
    printf("The sum total of the numbers is: %d\n",sum);

    printf("Do you want to enter more numbers ?Press Y/N: \n");
    getchar();
    scanf("%c",&a);
    if(a == 'Y'){
        printf("You have entered: %c\n\n",a);
        ptr = realloc(old_ptr,sizeof(int)*n);

        printf("Enter the elements:\n");

    for(i = 0;i < n;i++){
        scanf("%d",ptr);
        sum = sum + *ptr;
        ptr++;
    }
    printf("The total of the numbers is: %d\n\n\n",sum);
    }
    if(a == 'N'){
        printf("Program finished!");
    }
    return 0;
}

需要进行的更改是:

  1. ptr = old_ptr 更改为 old_ptr=ptr。 原因:赋值运算符的结合性是从右到左。

  2. scanf("%d",&ptr)改为scanf("%d",ptr) 原因:ptr 持有所需的地址。不需要 &.

  3. 放入getchar函数读取多余的\n

  4. 删除 printf 语句中多余的 \n

经过这些修改后,它起作用了。请看图