我正在尝试将输入输入到数组中,直到用户输入 -1 退出输入模式。
当输入 -1 时,此代码块中发生了一些奇怪的事情,但前提是至少输入了两个值。
#define ARRAYSIZE 100
int input[ARRAYSIZE];
int i=0;
do {
printf("Enter data #%d or -1 to exit: ", i);
scanf("%d", &input[i]);
} while(input[i++] != -1 && i<ARRAYSIZE)
代码将无限期挂起。我在两个不同的架构上编译运行,但是在gdb中运行没有出现问题。
插入 print 语句显示代码确实卡在 scanf 语句处。
有谁知道是什么原因造成的?
最佳答案
你从来没有检查你保存的数据的值(它是检查下一个未初始化的元素),do while 更合适
#define ARRAYSIZE 100
int input[ARRAYSIZE],i=0;
do {printf("Enter data #%d or -1 to exit: ", i);
scanf("%d", &input[i]);
}while(input[i] != -1 && ++i<ARRAYSIZE);
//if this is main() you need a return 0; here also or it will hang
关于C 代码卡在 scanf() 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666396/