Thread: C noob - getchar() help

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    2

    C noob - getchar() help

    Hi all,

    I'm just looking for some quick info to wrap my brain around how this is supposed to work. For a program for school I need to use the getchar() function to run through an array of chars and perform some tasks, but it also needs to be checking for some things like a "-1" to end the program and "\n" to force a new line for example. My question is how can I check for a -1 or \n if it's an array of chars? When I have my program try to check for those it just spits out errors about it being more than a single character, which is what I would have expected, yet the program specs spell out that's how it needs to work...

    The only thing I can think is to create two steps, basically if you encounter a - or a \, check the next character for a 1 or n. Is that what I probably need to do, or is there actually a way to fit -1 and \n in to single char elements in an array of chars?

    Thanks in advance for any info =)

    -Adam

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    getchar() wont read from an array of chars, it reads from the standard input device, one character at a time.

    You're right, -1 and \n are each 2 characters, so you can't do a single character comparison to find them. The easiest way is the two-step method you described, though I wouldn't "advance" through the input when getting a - or \. Instead, I would keep the previous char in a separate variable. Something like this:
    Code:
    int prev_char, curr_char;
    ...
    prev_char = -1;  // sentinel value, can't be mistaked of '-' or '\'
    while ((curr_char = getchar()) != EOF) {
        // check prev_char for - or \ and curr_char for 1 or n
        ...
        prev_char = curr_char;  // update prev_char for next iteration
    }
    That is only one place you have to deal with end of input or errors. The alternative is calling getchar() again inside the loop, if you get a '-' or '\\', and having to check for and handle end of input/error there too.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    2
    Oooh ok, that makes sense. Thanks for clearing that up and the advice on better ways of approaching the issue!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar
    By Niss in forum C Programming
    Replies: 4
    Last Post: 10-31-2008, 11:13 AM
  2. Can someone try getchar() please?
    By znum in forum C Programming
    Replies: 3
    Last Post: 05-12-2008, 04:14 PM
  3. getchar
    By pktcperlc++java in forum C++ Programming
    Replies: 4
    Last Post: 02-13-2005, 08:31 PM
  4. need help with getchar
    By sdogg45 in forum C Programming
    Replies: 17
    Last Post: 02-26-2004, 05:39 PM
  5. getchar()
    By shiju in forum C Programming
    Replies: 17
    Last Post: 12-06-2003, 09:13 PM