5

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?
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
MaddieSun
  • 101
  • 8
  • Sort of -- the read happens as soon as `x = getchar();` is executed, not the next time `x` is used. – Tavian Barnes May 26 '16 at 17:18
  • What you do with the return value of any function, including `getchar()`, has no impact whatever on what the function itself does when you call it. In particular, assigning the return value to a variable has no such impact. There are other factors that modulate function behavior, such as the values of their arguments, but functions neither know nor care what you do with their return values. – John Bollinger May 26 '16 at 17:25

1 Answers1

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261