Chapter Contents |
Previous |
Next |
getchar |
Portability: | ISO/ANSI C conforming, UNIX compatible |
SYNOPSIS | |
DESCRIPTION | |
RETURN VALUE | |
IMPLEMENTATION | |
EXAMPLE | |
RELATED FUNCTIONS | |
SEE ALSO |
SYNOPSIS |
#include <stdio.h> int getchar(void);
DESCRIPTION |
getchar
reads a character from the stream
stdin
.
RETURN VALUE |
getchar
returns the next input character or
EOF
if no character can be read.
IMPLEMENTATION |
getchar
is a macro that expands into
getc(stdin)
.
EXAMPLE |
#include <ctype.h> #include <stdio.h> #include <stdlib.h> main() { char filename[60]; int words = 0, lines = 0, bytes = 0; int spacing = 1; int ch; puts("Enter the input file name:"); memcpy(filename, "tso:", 4); gets(filename+4); if (freopen(filename, "r", stdin) == 0){ puts("File could not be opened."); exit(EXIT_FAILURE); } /* Read the file and count bytes, lines, and words. */ for(;;){ ch = getchar(); if (ch == EOF) break; ++bytes; if (ch == '\n') ++lines; /* If the input character is a nonspace character */ /* after a space character, start a new word. */ if (isspace(ch)) spacing = 1; else if(spacing){ spacing = 0; ++words; } } printf("The input file contains %d bytes\n", bytes); printf("%d lines and %d words.\n", lines, words); exit(EXIT_SUCCESS); }
RELATED FUNCTIONS |
SEE ALSO |
Chapter Contents |
Previous |
Next |
Top of Page |
Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.