I am using getchar() while writing a program in C (scanf is not allowed yet at this point in the course.) I was wondering if every single time I call it if it moves to the next one; including during assignment operations. For example; I am trying to read in a double from the console; and decide if it has a negative sign on the front. If it does; I want to assign a variable neg to be 1 (so that I can tell if the end result should be returned negative) and then I want to move to the next character to do my actual double calculations and what not. ex)
int x = getchar();
int neg = 0;
if(x == '-') {
neg = 1;
x = getchar(); // will this make it so the next time I use the x
} // variable it will be past the negative sign and to the
//first actual digit?
Yes, every time you call getchar() it will read the next character (provided there is next character to read).
Quoting C11, chapter §7.21.7.6
The
getchar()function returns the next character from the input stream pointed to bystdin.
In case there is nothing valid to be read,
If the stream is at end-of-file, the end-of-file indicator for the stream is set and
getcharreturnsEOF. If a read error occurs, the error indicator for the stream is set andgetcharreturnsEOF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With