Search code examples
cintgetchar

Get whole number from input using only getchar() and convert to int


For a school assignment i have to make a C program that reads a whole number, that may be preceded by a '+' or '-'. i can only use getchar(). I can convert a single char to an int using int i = ch - '0' but I want to read in multiple chars. besides that I need to check if the input is correct (eq. no not-numerical charachters)

I have this so far:

int main(void) {
    int i;
    char ch;

    printf("voer een getal in: ");

    while ((ch = getchar()) != '\n') {
        i = ch - '0';

    }

    printf("het ingevoerde getal is: %d\n", i);
    return EXIT_SUCCES;
}

Edit: I get that this isn't really the place for problems like this (I should learn to fix it myself, not get others to fix it for me) but I didn't know what to do anymore. thanks you for guiding me to the right path


Solution

  • Reading in multiple characters, and determine whether positive, negative, and value:

     int sign = 1;
     ch = getchar(); //look at first char (might be a sign indicator)
     if((ch == '-') || (ch == '+')) //consume first char if either `-` or `+`
     {
          if(ch == '-') sign = -1;
     }
     else  //first char non-sign - handle as digit
     {
         if (ch > '9' || ch < '0')
                continue; // or print an error and exit
         i *= 10;
         i += ch - '0';
     }
     while ((ch = getchar()) != '\n') //get remaining chars (assume no embedded sign chars)
     {
         if (ch > '9' || ch < '0')
                continue; // or print an error and exit
         i *= 10;
         i += ch - '0';
     }
     i *= sign; //apply sign to value