I want to understand how is getchar()
function is working here?
I read getchar()
returns the next character from stdin
, or EOF
if the end of file is reached.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int decimal;
while(!isdigit(decimal=getchar()));
cout<<decimal;
}
I give input 25. It outputs 50. I don't understand why? How is it giving 50.
getchar()
reads a single character from the input stream and returns it's value. In your case, that is the character '2'
. Most implementations (including yours it seems) use ASCII encoding where the character '2'
has the value 50
. The value assigned to decimal
is therefore 50
. Since decimal
is an int
, std::cout
interprets it as a numeric value and prints it accordingly.