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

标签 c stdout stdin stderr

我正在编写一个名为 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;

}

在 ubuntu 中我运行 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 将相应的参数解释为字符。

关于输出字符的 C 程序会生成整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446758/

相关文章:

c - 在C中使用<file.txt从stdin文件读取内容,禁止fopen

c - 构建C程序时如何解决CodeBlocks中的这个 'Multiple Definitions of'错误?

python - 在 structlog 中设置渲染器树

python - 捕获标准输出以供以后重播的明智方法?

python - 在 Python 中设置只读属性?

c - 写入 stdin 并从 stdout 读取(UNIX/LINUX/C 编程)

c - fscanf() fclose() 或读取文件退出并结束程序

c unix execl 不适用于用 strcat 构建的字符串

c - 从命令行读取可变行文件并存储

c - c标准库中的stdin在哪里定义?