该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
。经过这些修改,它起作用了。请看图片。
关于c - 为什么在不等待用户输入的情况下退出程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62994755/