为什么在getchar函数,而第一次迭代后不执行? [英] why does getchar in while not execute after first iteration?

查看:176
本文介绍了为什么在getchar函数,而第一次迭代后不执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序来通过从字符输入字符读取并打印输出,这里是我的code:

I wrote a program to read from input character by character and print it to output and here is my code:

#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

但它应该有这样的结果:

but it should have this result:

a
log1
a
log2

什么是错的这个计划?

what's wrong with this program?

推荐答案

您提供输入和换行

a(my input)  You are giving a and newline

//this is because of a 
log1
a
log2 

//this is because of newline
log1


log2

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

Check for newline and avoid printing Newline.

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

这篇关于为什么在getchar函数,而第一次迭代后不执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆