-
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
-
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.
-
Oooh ok, that makes sense. Thanks for clearing that up and the advice on better ways of approaching the issue!!