-2

How do I write the return value from getchar() function to a file? I tried the following and it wrote integers to the file. Preferably in a C++ solution?

myFile.open("somefile.txt", ios::app);
myfile<<getc(fd);
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • In C, at any rate, `getchar()` takes no argument — `getc()` takes a file stream argument. In what way did your code not work? You've not shown how you open the `myfile` stream (or the `getchar()` stream). – Jonathan Leffler Nov 01 '18 at 01:32
  • 2
    "did not work" is a poor problem description. Please see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – M.M Nov 01 '18 at 01:33
  • What is `myfile`? If it is a `FILE *`, use `fputc` or `putc`. – Arkku Nov 01 '18 at 01:34
  • Nevermind I think it wrote some numbers to the file. – Lightsout Nov 01 '18 at 01:40
  • "some numbers" being the return value of `getc` – M.M Nov 01 '18 at 02:16
  • Although `getc` is not part of standard C or C++, it is a common extension. As with any function, you should begin by [reading the documentation](https://en.m.wikibooks.org/wiki/C_Programming/stdio.h/getc). Especially the part that tells you the type of the value that it returns. – Pete Becker Nov 01 '18 at 02:18
  • @PeteBecker: C11 [§7.21.7.5 The `getc` function](https://port70.net/~nsz/c/c11/n1570.html#7.21.7.5). Are you thinking of the `getch()` function which is not a part of standard C. – Jonathan Leffler Nov 01 '18 at 13:31
  • @JonathanLeffler -- no, I was thinking of `getc`, which didn't show up in my web search late last night. But it's there now. Nevertheless, its return type is what matters. – Pete Becker Nov 01 '18 at 15:16

1 Answers1

2

It may seem counter-intuitive, but getc does not return a char - it returns an int. This is so that there's an out-of-range value to use to indicate end of file.

The behavior of << is vastly different between a char and an int. For char it puts out the character as you'd expect, but for int it outputs the decimal representation of a number.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622