如果 for 循环是最后一次迭代(或仅一次迭代),则不会执行循环体中的最后一条语句。即使它只包含 printf() 语句,并且还会跳过函数体中接下来的语句,也无法正常工作。代码如下:
void build()
{
int i;
system("clear");
printf("\nBuild the table");
printf("\n");
printf("\nMaximum number of entries ------> 20");
printf("\nHow many do u want------>");
scanf("%d",&num);
printf("\nEnter the following items\n");
for(i=0;i<num;i++)
{
printf("\nName ");
scanf("%s",emp[i].name);
printf("\nCode");
scanf("%ld",&emp[i].code);
printf("\nDesignation");
scanf("%s",emp[i].designation);
printf("\nAge");
scanf("%d",&emp[i].age);
printf("\nYears of experience");
scanf("%d",&emp[i].exp);
printf("\nHello everyone");
}
for(i=0;i<num;i++)
{
printf("\n%s",emp[i].name);
printf("\n%ld",emp[i].code);
printf("\n%s",emp[i].designation);
printf("\n%d",emp[i].age);
printf("\n%d",emp[i].exp);
}
printf("\nGoing to main menu");
}
struct employee
{
char name[20];
long int code;
char designation[20];
int exp,age;
};
struct employee emp[max];
我在函数中的 for 循环中遇到了同样的问题,上面的结构声明是 max=20;
最佳答案
你的分析是错误的——问题不在于执行,而在于行缓冲。
printf
有几种优化 io 的模式——最常见的误解是行缓冲,当遇到换行符时它会自动刷新。
所以
printf("\nGoing to main menu");
不会刷新,因为换行符不在末尾p>
哪里
printf("Going to main menu\n");
会冲水。如果您必须按照自己的方式进行操作,请使用 fflush,例如
printf("\nGoing to main menu");
fflush(stdout);
强制冲洗
关于c - 循环不执行 C 中最后一次迭代中的最后一条语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35965876/