tags:

views:

145

answers:

5

the output should be something like this:

Enter Character : a
Echo : a

I wrote

int c;
  while (c != EOF)
    {
      printf("\n Enter input: ");
      c = getchar();
      putchar(c);
    }

But I get two Enter Input after the echos.

+2  A: 

Homework?

If so, I won't give a complete answer/ You've probably got buffered input - the user needs to enter return before anything is handed back to your program. You need to find out how to turn this off.

(this is dependent on the environment of your program - if you could give more details of platform and how you are running the program, we could give better answers)

Paul
+2  A: 

Two characters are retrieved during input. You need to throw away the carriage return.

int c = 0; 
int cr;
  while (c != EOF) 
    { 
      printf("\n Enter input: "); 
      c = getchar(); 
      cr = getchar();  /* Read and discard the carriage return */
      putchar(c); 
    } 
Starkey
Your `c` is not initialized. It can can have the value of `EOF` to start with.
codaddict
@codaddict - You're right. I just copied the OP's code. I'll fix it.
Starkey
What if the user enters two characters before pressing Enter?
Paul
A: 

But I get two Enter Input after the echos.

It is because getchar() is reading the newline character from buffer.use two getchar() and it'd solve your problem.

Farhan
A: 

Why don't you use scanf instead?

Example:

char str[50];

printf("\n Enter input: ");
scanf("%[^\n]+", str);

printf(" Echo : %s", str);

return 0;

Outputs

 
 Enter input: xx
 Echo : xx

scanf reference

BrunoLM
`scanf` does regex?
leppie
You should also limit scanf input to 49 chars, otherwise you may risk a buffer overrun.
Matteo Italia
+1  A: 

take fgets eg:

char c[2];
if( fgets( c, 2, stdin ) )
  putchar( *c );
else
  puts("EOF");

and you dont have any problems with getchar/scanf(%c)/'\n' and so on.