Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#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
Posted
Updated 13-Mar-17 17:52pm

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();
    }
 
Share this answer
 
try getch(). It does not wait for <enter> and does not echo to console either.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900