-1

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)

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 1
    Your code appears to succeed in both of your examples. Can you give an example of it failing? – Beta May 04 '19 at 01:15
  • The `while` loop is calling `getchar()` multiple times. It calls it once in the `while()` condition, then it calls it again in the first line. So the character that it tested in `while()` is being ignored. Then it calls it again in `if ((ch == getchar()) == EOF)`, so the character it read on the previous line is ignored. – Barmar May 04 '19 at 01:18
  • @Beta I think the examples at the bottom are what it's supposed to return, not what it actually returns. – Barmar May 04 '19 at 01:19
  • 1
    [`ch` must be an `int`, not `char`](https://stackoverflow.com/questions/35356322/difference-between-int-and-char-in-getchar-fgetc-and-putchar-fputc) – Antti Haapala -- Слава Україні May 04 '19 at 11:34
  • @AlistairAlva: you can accept one of the answers by clicking on the grey checkmark below its score – chqrlie May 09 '19 at 06:29

2 Answers2

1

You're calling getchar() too many times in your while loop. Each of them is discarding the result of the previous call. You should just use the result of the getchar() call in the while() condition, not call it again.

You're also not saving the character you read before the loop into the accumulator.

You have a typo in ch = '0', that should be ch - '0'.

You need to declare ch to be int, not char, because EOF is not a character.

EXIT_FAILURE should be exit(EXIT_FAILURE). And you shouldn't put break; before it, since that will terminate the loop, skipping over the exit() call.

You can initialize negative to 1, so at the end you can just multiply by it without having to test the value first. In this case, a better name for the variable is sign.

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>

int main() {
    int accumulator = 0;
    int ch;
    int sign = 1;

    ch = getchar();
    if (ch == '-') {
        sign = -1;
        ch = getchar();
    }

    if (!isdigit(ch)) {
        puts("\nError: Not valid number.\nPlease try again");
        exit(EXIT_FAILURE);
    }

    accumulator = ch - '0';

    while ((ch = getchar()) != '\n' && ch != EOF) {
        if (!isdigit(ch)) {
            puts("\nError: Not valid number.\nPlease try again");
            exit(EXIT_FAILURE);
        }

        accumulator *= 10;
        accumulator += (ch - '0');
    }

    accumulator *= sign;

    printf("%d", accumulator);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

There are multiple problems in your code:

  • ch must be defined with type int to accommodate for all values returned by getchar().
  • you should test for EOF at the top of the while loop.
  • EXIT_FAILURE is an argument value for the exit() function. Use it as exit(EXIT_FAILURE).
  • you re-read a new character inside the while loop body instead of handling ch.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int accumulator = 0;
    int ch;
    int negative = 0;

    ch = getchar();
    if (ch == '-') {
        negative = -1;
        ch = getchar();
    } else (if (ch == '+') {
        ch = getchar();
    }   

    if (isdigit(ch) == 0) {
        puts("\nError: Not valid number.\nPlease try again");
        exit(EXIT_FAILURE);
    }

    while ((ch = getchar()) != EOF && ch != '\n') {
        if (!isdigit(ch)) {
            puts("\nError: Not valid number.\nPlease try again");
            exit(EXIT_FAILURE);
        }
        accumulator = accumulator * 10 + (ch = '0');
    }
    if (negative < 0)
        accumulator = -accumulator;

    printf("%d\n", accumulator);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189