输出字符的C程序将生成整数

输出字符的C程序将生成整数,c,stdout,stdin,stderr,C,Stdout,Stdin,Stderr,我正在编写一个名为split.c的程序,它从stdin中提取一个input.txt文件作为输入,然后将输入文件中的每一个字发送到stdout和stderr 我目前的代码如下: #include <stdio.h> int main(){ int input; // keep getting characters until end-of-file while ((input = fgetc(stdin)) != EOF){ // prints to stdout

我正在编写一个名为split.c的程序,它从stdin中提取一个input.txt文件作为输入,然后将输入文件中的每一个字发送到stdoutstderr

我目前的代码如下:

#include <stdio.h>

int main(){
  int input;

  // keep getting characters until end-of-file
  while ((input = fgetc(stdin)) != EOF){

  // prints to stdout
  fprintf(stdout, "%d", input);
  if(input == " ")
      printf("\n");   // encounters whitespace so print new line

  // prints to stderr
  fprintf(stderr, "%d", input);
  if(input == " ")
      printf("\n");   // encounters whitespace so print new line

  }

  return 0;

}
myerr.txt
中:

"Is
code
my
working?"
相反,我在这两个文件中都得到了以下内容,数量巨大:

6511032731101001051181051001179710...............
你知道代码有什么问题吗?我的思维过程错了吗?其思想是,它获取输入文件,读取每个字符,然后,当找到空白时,它在stdout中打印新行,然后执行相同的操作,但现在打印到stderr,直到达到EOF


我仍在学习使用stdin/out/err的输入和输出(双关语:)。因此,如果编码不正确,我并不感到惊讶。感谢您的指导

您使用的是将相应参数解释为数字的
%d
说明符。您应该使用
%c
将相应的参数解释为字符。

如rlee827所述,数字来自
%d
。另外,
input==''
需要是
input=''
。您还将所有内容同时打印到stdout和stderr;您还没有真正的代码来正确地进行替换。您可能希望有一个包含两个内部循环的外部循环:第一个内部循环将读取并复制到stdout,直到找到一个空格,然后第二个内部循环将对stderr执行相同的操作。不过,如果您只打印一个字符而不打印其他字符,您可能希望使用
putc
而不是
fprintf(…,“%c”,…)
因为它更简单、更高效。