I have an assignment where I'm supposed to make a simple arithmetic calculator in C that takes an input of a number, an operator, and a second number and performs the operation and outputs it. Sounds pretty simple right?
I'm limited to using specifically getchar()
and putchar()
for number input. This means that I have to read the whole input one char at a time... and I'm confused as to how I would read two chars of a number (9
and 1
of 91
for example) as one number. If getchar()
read from right to left, this would be a different story. But unfortunately, it is not...
I would appreciate any pointers!
Here is some pseudo-code:
c = getchar()
num = 0
while isdigit(c)
num = (num * 10) + (c - '0')
c = getchar()
This accumulates the number, recognizing that each new digit to the right effectively multiplies the digits seen already by 10. It stops accumulating when a non-digit is seen, so parsing strings like 91+3 works.