C程序输出字符而不是产生整数

C program to output characters produces integers instead

我正在编写一个名为 split.c 的程序,它从 stdininput.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;

}

在ubuntu I 运行 make 然后命令./split < test/input.txt > myout.txt 2> myerr.txt

预期的输出应该是,例如。

如果input.txt有以下内容:"Is my code working?"

输出应该是:

myout.txt中:

"Is
code

myerr.txt中:

my
working?"

相反,我在两个文件中都得到了以下内容,数量巨大:

6511032731101001051181051001179710...............

知道代码可能有什么问题吗?我的思维过程错了吗?这个想法是它获取输入文件,读取每个字符,然后,当发现空格时,它在 stdout 中打印一个新行,然后做同样的事情,但现在打印到stderr 直到到达 EOF。

我仍在学习使用 stdin/out/err 的来龙去脉(双关语 :)),所以如果我编码不正确,我不会感到惊讶.任何指导表示赞赏!

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