C编程中的Getchar() [英] Getchar() in C programming

查看:49
本文介绍了C编程中的Getchar()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include< stdio.h>

int main()

{

char ch;

printf(\ n输入字符\ n);

ch = getchar();

while(ch!='1')

{

putchar(ch);

ch = getchar();

}

返回0 ;

}



我的尝试:



1.首先,即使我输入1作为输入,根据while循环它应该终止程序,但它不是。

2.once我进入了输入,我希望我的程序转到新行并允许我输入输入,但是一旦我输入,它只是粘贴输入我给的。



例如:

输入:

sandeep 67865



1

输出应该是:

sandeep 67865

#include<stdio.h>
int main()
{
char ch;
printf("\nEnter the character\n");
ch=getchar();
while(ch!='1')
{
putchar(ch);
ch=getchar();
}
return 0;
}

What I have tried:

1.First thing ,even though i entered 1 as a input,according to a while loop it should terminate the program,but it is not.
2.once i entered the enter,i want my program to go to new line and allow me to type the input,but once i type enter ,it is just pasting the input what i have given.

Example:
Input:
sandeep 67865

1
Output should be:
sandeep 67865

推荐答案

这是因为一旦用户按下一个键,getchar就不会返回:它从中读取一个字符标准输入流,该数据仅在用户按下ENTER时显示,表示他对输入的内容感到满意。如果没有,那么他将无法退格以更改他输入的内容。



所以发生的事情是第一次调用getchar不会返回直到用户完成该行,此时它回显(或用你的术语粘贴)直到ENTER的所有字符。



更改循环,你会明白我的意思:

That's because getchar doesn't return as soon as the user presses a key: it reads a character from the standard input stream, and that data is only available when the user presses ENTER to indicate he is happy with what he typed. If it didn't, then he would be unable to to backspace to change what he typed.

So what is happening is that the first call to getchar does not return until the user has finished the line, at which point it "echoes" (or "pastes" in your terms) all teh characters up to the ENTER.

Change the loop, and you'll see what I mean:
while(ch!='1')
    {
    printf("\nThe character was: ");
    putchar(ch);
    ch=getchar();
    }


尝试getch()。它不等待< enter>并且不会回显到控制台。
try getch(). It does not wait for <enter> and does not echo to console either.


这篇关于C编程中的Getchar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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