PDA

View Full Version : Help Understanding getchar() and putchar() in C




bftiedt
Apr 6, 2012, 09:30 AM
Hey guys I'm moving on with my quest in learning C. I have come to learning about getchar and putchar. The problem is Im having a little trouble understanding just how the work within the code itself. I have
Looked for examples of how they are used and the result they produce but haven't found anything that helps. If anyone could help explain and maybe provide something that helps with the understanding that would be great.

Thanks



willieva
Apr 6, 2012, 09:52 AM
If you had a more specific question it would be easier to help.

You can use getchar like this:
int i = getchar();
This will make the program pause until a character has been input and the return key pressed. The ascii value of that character will be stored in i;

getchar(c) outputs the value of c, which is of type char.
char c = 'c';
putchar(c);

jared_kipe
Apr 6, 2012, 10:13 AM
FILE *textFile = fopen("text.txt", "w");
if (textFile != NULL ) {
char c = '\n';
do {
c = getchar();
fputc(c, textFile);
} while (c != '\n');
fclose(textFile);
} else {
printf("Ooops no file to write to");
}

Now technically the prototype for getchar() returns an int, but I used a char.

putchar() is similar to my fputc but with standard out by default (so no second argument).


char *string = "I am a happy string!\n";
int i = 0;
while (string[i] != '\0') {
putchar(string[i]);
i++;
}


----------

If you had a more specific question it would be easier to help.

You can use getchar like this:
int i = getchar();
This will make the program pause until a character has been input and the return key pressed. The ascii value of that character will be stored in i;

getchar(c) outputs the value of c, which is of type char.
char c = 'c';
putchar(c);

The Red part is not true. getchar() consumes a character from stdin and will consume carriage and new line characters just as easily.

Orange part is a typo.

firewood
Apr 6, 2012, 02:33 PM
The Red part is not true. getchar() consumes a character from stdin and will consume carriage and new line characters just as easily.

If stdin is from the keyboard, and the keyboard input is buffered, then there will be no characters in stdin to consume until after the return key is pressed. It may be possible to change this buffering behavior with an ioctl call.

jared_kipe
Apr 6, 2012, 02:36 PM
If stdin is from the keyboard, and the keyboard input is buffered, then there will be no characters in stdin to consume until after the return key is pressed. It may be possible to change this buffering behavior with an ioctl call.

Ok. Guess I haven't run into that using normal terminal stuff. Regardless, thats not a feature/limitation of getchar() as much as it is a limitation of the stream source. getchar() does not specifically wait for a carriage return.