Misplaced Pages

putchar

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.

This is an old revision of this page, as edited by Deryck Chan (talk | contribs) at 08:10, 21 February 2006 (See also). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Revision as of 08:10, 21 February 2006 by Deryck Chan (talk | contribs) (See also)(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)


putchar is a function in C programming language that writes a single character to the standard output. Its prototype is as follows:

int putchar (int character)

The character to be printed is fed into the function as an argument, and if the writing is successful, the argument character is returned. Otherwise, end-of-file is returned.

The putchar function is specified in the C standard library header file stdio.h.

Sample usage

The following program uses getchar to read characters into an array and print them out using the putchar function after an end-of-file character is found.

#include <stdio.h>
int main() {
  char str;
  int n = 0;
  while (!feof(stdin)) {
    str = getchar();
    ++n;
  }
  for (int i = 0; i < n; ++i) {
    putchar(str);
  }
  return 0;
}

The function specifies the reading length's maximum value at 1000 characters; however if the end-of-file character doesn't come up after 1000 characters are read, different operating systems and different compilers will give different results: Some cases will terminate the program at a segmentation fault, while some others will read the remaining string into the non-allocated area of the memory, possibly causing errors to other programs.

See also

References

Category: