[英]C: why does my program not continue after while loop? (scanf)
I'm currently learning C
and wanted to write a program that takes a number ganzeZahl
to determine array length.我目前正在学习
C
并想编写一个程序,该程序需要一个数字ganzeZahl
来确定数组长度。
Then you have to input the numbers being stored in that array of size n
and after that it's supposed to do a selection sort (which I cut out here, because my program doesn't even reach to that part).然后你必须输入存储在大小为
n
的数组中的数字,然后它应该进行选择排序(我在这里剪掉了,因为我的程序甚至没有到达那个部分)。
I can't get past the while loop whenever I try to run it.每当我尝试运行它时,我都无法通过 while 循环。 It compiles fine.
它编译得很好。 It never reaches the
printf(";!!--------!!!");
它永远不会到达
printf(";!!--------!!!");
//this part isn't reached for some reason? //由于某种原因,这部分没有到达? test5.
测试5。
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
Your program does execute correctly, and eventually reaches the last printf
call.您的程序确实执行正确,并最终到达最后一个
printf
调用。
When, it enters the while
loop, it keeps on calling scanf
, what causes it to stop and wait until you enter a value every iteration.当它进入
while
循环时,它会继续调用scanf
,是什么导致它停止并等待,直到您每次迭代都输入一个值。 If you provide ganzeZahl
inputs (enter a number and press 'enter'), it will complete the loop and proceed.如果您提供
ganzeZahl
输入(输入数字并按“输入”),它将完成循环并继续。 I guess that if you add a printf
before scanf
within the loop, it should be more intuitive.我想如果你在循环内的
scanf
之前添加一个printf
,它应该更直观。
for(int z = 0; z < ganzeZahl; z++){
printf("%d\n", array[z]);
The array is not initialized and so you can't print the array yet.该数组未初始化,因此您还不能打印该数组。
Actually you messed up with the order of code.The while loop should come first and then the for loop.实际上你搞砸了代码的顺序。while循环应该先出现,然后是for循环。 I have corrected your code below.
我在下面更正了您的代码。 Happy coding!
快乐编码!
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.