Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using getchar() in C; does it move to the next char every time I use it? Including within assignment operations?

Tags:

c

getchar

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?
like image 410
MaddieSun Avatar asked May 26 '16 17:05

MaddieSun


1 Answers

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 by stdin.

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 getchar returns EOF. If a read error occurs, the error indicator for the stream is set and getchar returns EOF.

like image 109
Sourav Ghosh Avatar answered Dec 21 '22 02:12

Sourav Ghosh