C语言 如何用 C 编写 echo 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3901469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:39:12  来源:igfitidea点击:

How do I write an echo program in C?

c

提问by unj2

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.

但是在回声之后我得到了两个 Enter Input。

采纳答案by Starkey

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

回答by The Archetypal Paul

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.

如果是这样,我不会给出完整的答案/您可能已经获得了缓冲输入 - 用户需要在将任何内容交还给您的程序之前输入 return 。您需要了解如何关闭此功能。

(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)

(这取决于您的程序的环境 - 如果您能提供更多有关平台的详细信息以及您如何运行程序,我们可以提供更好的答案)

回答by user411313

take fgets eg:

采取 fgets 例如:

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.

并且您对 getchar/scanf(%c)/'\n' 等没有任何问题。

回答by d mohan

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

回答by BrunoLM

Why don't you use scanfinstead?

你为什么不scanf改用?

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

扫描参考