gpt4 book ai didi

c - 为什么在不等待用户输入的情况下退出程序?

转载 作者:行者123 更新时间:2023-12-02 07:19:04 32 4
gpt4 key购买 nike

该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;
}
所需的更改是:
  • ptr = old_ptr更改为old_ptr=ptr
    原因:赋值运算符的关联性从右到左。
  • scanf("%d",&ptr)更改为scanf("%d",ptr)原因:ptr保留了所需的地址。无需&
  • 放入getchar函数以读取多余的\n
  • 删除\n语句中多余的printf

  • 经过这些修改,它起作用了。请看图片。 enter image description here

    关于c - 为什么在不等待用户输入的情况下退出程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62994755/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com