c - 为什么 while 中的 getchar 在第一次迭代后不执行?

标签 c

我编写了一个程序来逐个字符地读取输入并将其打印到输出,这是我的代码:

#include <stdio.h>

main()
{

    int c;
    while((c = getchar()) != EOF)
    {
        printf("%s\n", "log1");
        printf("%c\n", c);
        printf("%s\n", "log2");
    }

}

这是结果:

a(my input)
log1
a
log2
log1


log2

但它应该有这样的结果:

a
log1
a
log2

这个程序有什么问题?

最佳答案

您输入 a 和换行符

a(my input)  You are giving a and newline

//this is because of a 
log1
a
log2 

//this is because of newline
log1


log2

检查换行符并避免打印换行符。

    while((c = getchar()) != EOF)
        {
            if(c!='\n')
               {  
                printf("%s\n", "log1");
                printf("%c\n", c);
                printf("%s\n", "log2");
               }
        }

关于c - 为什么 while 中的 getchar 在第一次迭代后不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342434/

相关文章:

c - 如何为头文件中定义(声明?)的数组分配内存?

c - 为什么相同的输入(0)我的输出会增加?

c++ - 如何从 C/C++ 在 Linux 中设置 IRQ 优先级?

c - 将数据值列表写入 .dat 文件以在 GNUplot 中绘制(在 C 中)

c - Structs的动态数组,删除元素

c - 如何写入命名管道而不是等待读取管道

c - 从麦克风获取音频

c程序for循环: execution sequence

c - 如何将无符号 64 位值存储在两个有符号整数中并恢复它们?

c++ - 让 GDC 前端发出中间 C/C++ 代码?