Programming noob here. I have an assignment where I have to read in a number using getchar()
and perform some operations on it. The number can either be a positive or negative number. This is the segment of my code that takes in input. I can't find the issue but it returns something else.
I am using the general way of converting characters to integers by first multiplying an accumulator by 10
, then converting the character to its digit equivalent using (ch -'0')
and adding it to the accumulator,
I have tried removing the validation for negative numbers but it still doesn't make a difference.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
int main() {
int accumulator = 0;
char ch;
int negative = 0;
ch = getchar();
if (ch == '-') {
negative = -1;
ch = getchar();
}
if (isdigit(ch) == 0) {
puts("\nError: Not valid number.\nPlease try again");
EXIT_FAILURE;
}
while ((ch = getchar()) != '\n') {
ch = getchar();
if ((ch = getchar()) == EOF) {
break;
}
if (!isdigit(ch)) {
puts("\nError: Not valid number.\nPlease try again");
break;
EXIT_FAILURE;
}
accumulator = accumulator * 10;
accumulator = (ch = '0') + accumulator;
}
if (negative == -1)
accumulator = accumulator * negative;
printf("%d", accumulator);
}
Example
Input: 2351
Output: 2351
(Using getchar
)
Input: -5689
Output: -5689
(Using getchar
)