Friday, July 29, 2011

getc/getchar why doesn't it wait?

So getc is basically the same as getchar but to get the same effect
getc(stdin) = getchar basically.
From the above link:
Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character.

What this means is that this is not a "wait for input" type operation, it literally will grab the next character from the stdin stream unless you find a way to prevent it,


Example function from code to be used:

char getMathSymbol()
{
while (getchar() == '\n') // use this or getchar will not wait for input.
{
// temp varaible
char userSymbol;
cout << "please enter yoru math symbol" << endl;
// need getchar to get a character from the console
      userSymbol = getchar();
      
//cout << "getchar done" << endl; // debug code
// return your symbol
return userSymbol;
}
}

For Example you entered in the following:


Enter your first number
1
Enter your second number
2
please enter yoru math symbol
+
3


Lets look at this again, with all (hidden) characters visible
Enter your first number\n
1\n
Enter your second number\n
2\n
please enter yoru math symbol\n
+\n
3



When you hit getMathSymbol
you are at this point:
Enter your first number\n
1\n
Enter your second number\n
2\n
please enter yoru math symbol\n

When you get the char, the \n is grabbed (which is why the "while loop works").

So what I suspect happens is that we hit that \n and since it's a valid character (not end of line or end of file) we grab the character and exit the function. (when the while loop is gone).

What happens if we read the last character to increment to the next char (which is EOF or EOL)?

char getMathSymbol()
{
//while (getchar() == '\n') // use this or getchar will not wait for input.
{
// temp varaible
char userSymbol;
cout << "please enter yoru math symbol" << endl;
// need getchar to get a character from the console
           userSymbol = getchar();
           userSymbol = getchar();
      
//cout << "getchar done" << endl; // debug code
// return your symbol
return userSymbol;
}
}

After compiling, it looks like it works, so what happens is that if there is a valid character the getchar returns immediately, if the next char isn't valid, then it waits until a valid char occurs.

Make sense?