unj2
unj2

Reputation: 53551

How do I write an echo program in C?

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.

Upvotes: 4

Views: 36363

Answers (5)

d mohan
d mohan

Reputation: 1

#include <stdio.h>
#include <conio.h>

main(){
    int number;
    char delimiter;
    printf("enter a line of positive integers\n");
    scanf("%d%c", &number, &delimiter);
    while(delimiter!='\n'){
        printf("%d", number);
        scanf("%d%c", &number, &delimiter);
    }
    printf("\n");
    getch();
}

Upvotes: 0

user411313
user411313

Reputation: 3990

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.

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100381

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

Upvotes: 0

Starkey
Starkey

Reputation: 9781

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); 
    } 

Upvotes: 3

The Archetypal Paul
The Archetypal Paul

Reputation: 41779

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)

Upvotes: 2

Related Questions