Help Understanding getchar() and putchar() in C

Discussion in 'Mac Programming' started by bftiedt, Apr 6, 2012.

  1. macrumors member

    Joined:
    Feb 12, 2008
    #1
    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
     
  2. macrumors 6502

    Joined:
    Mar 12, 2010
    #2
    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);
     
  3. macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #3
    Code:
        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).

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


    ----------

    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.
     
  4. macrumors 603

    Joined:
    Jul 29, 2003
    Location:
    Silicon Valley
    #4
    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.
     
  5. macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #5
    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.
     

Share This Page