Search code examples
cstdoutstdinstderr

C program to output characters produces integers instead


I'm writing a program called split.c that takes from the stdin an input.txt file as input and then sends every other word within the input file to stdout and stderr.

My current codes is as follows:

#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;

}

In ubuntu I run make then the command ./split < test/input.txt > myout.txt 2> myerr.txt

The expected output should be, for example.

If input.txt has the following: "Is my code working?"

The output should be:

In myout.txt:

"Is
code

In myerr.txt:

my
working?"

Instead I get the following in both files, a huge number:

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

Any idea was to what may be wrong with the code? Is my thought process wrong? The idea is that it gets the input file, reads each character and then, when a whitespace is found, it prints a new line in stdout, then does the same thing, but now printing to stderr until it reaches EOF.

I'm still learning the in's and out's (pun intended :) ) of using stdin/out/err so I'm not surprised if I'm not coding correctly. Any guidance is appreciated!


Solution

  • You are using the %d specifier that interprets the corresponding argument as a number. You should be using %c to interpret the corresponding argument as a character.