c - 循环不执行 C 中最后一次迭代中的最后一条语句?

标签 c for-loop

如果 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"); 

不会刷新,因为换行符不在末尾

哪里

printf("Going to main menu\n");  

会冲水。如果您必须按照自己的方式进行操作,请使用 fflush,例如

printf("\nGoing to main menu"); 
fflush(stdout);

强制冲洗

关于c - 循环不执行 C 中最后一次迭代中的最后一条语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35965876/

相关文章:

java - 用两个 for 循环简化计数(使用流)

java - 您如何从数组列表中提取项目并对它们进行计数,以便在 Java 中根据元素及其总计数(正确地)创建映射?

我的 C 程序中的字符输入错误?

Ceedling 项目文件无法识别路径和库

c - 作为位表示的空字符串输入

c - 多数 - 如果票数相等,如何打印多个获胜者?

php - for()中的mysql_fetch_array函数出现错误

VBA EXCEL 多个嵌套 FOR 循环,为表达式设置两个变量

c - 如何修复我的打印时间功能,使其不会慢 8 小时?

arrays - Swift 3 对数组中的大量数据进行排序