c - C中的不完整打印

标签 c structure

#include<stdio.h>
#define max 3

struct t
{
    char ch;
    char cH;
    int i;
};

int main()
{
    struct t test[max];
    int count=0,in=0;

    while(count < max)
    {
        printf("Enter small char\n");
        scanf("%c",&test[count].ch);
        getchar();          

        printf("Enter big char\n");
        scanf("%c",&test[count].cH);
        getchar();

        printf("Enter number\n");
        scanf("%i",&test[count].i);
        count++;
    }

    for(in=0;in<count;in++)
    {
        printf("%c %c %i\n",test[in].ch,test[in].cH,test[in].i);
        //printf("line%10i\n",in);
    }

    return 0;
}

对于以下输入:

a A 1
b B 2
c C 3

输出:

a A 1
2
3

为什么不打印第 2 行和第 3 行。错误是由于 getchar() 函数引起的吗? 还有什么更好的刷新输入?

最佳答案

当您读取一个整数时,scanf 会将“\n”保留在缓冲区中(当您按下回车键时),它会被您的下一个 scanf 捕获。所以,只需要在读取整数后添加一个新的 getchar() 即可。

printf("Enter number\n");
scanf("%i",&test[count].i);
count++;
getchar();

关于c - C中的不完整打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039089/

相关文章:

c - C语言: "Program ended with exit code: 0"如何去掉这一行

c - 当我们用完 Cortex M3 上的内存时会发生什么

c - 如何在 C 中计算 2⁶⁴/n?

c - C 语言的服务器/客户端程序 : how to send correctly dimension of structure elements via socket?

c - 在C中解密文件的功能?

c - 不同链表结构的函数addnode

c - 如何从 C 语言文件中将每一行读入整数数组?

c - 使用指针实现堆栈

arrays - 如何将结构数组切片成行,而不是列?

c - 结构中的无符号数据类型