Question

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

Était-ce utile?

La solution 3

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

Autres conseils

This should get you started:

int main(void) {
    int i = 0;
    int ch;

    printf("voer een getal in: ");

    while ((ch = getchar()) != '\n') {
        if (ch > '9' || ch < '0')
            continue; // or print an error and exit
        i *= 10;
        i += ch - '0';
    }

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

I'll leave detecting the potential + / - sign as an exercise.

If your school allows you to use shift operators then here is a quick way to get integer from the user and as per their requirements you can show the + or - sign preceding the integer. But remember not to just copy paste it. Understand the code first.

    int main(){
        int i = 0;
        char c;
        char sign = 43;

        printf("voer een getal in:\n");
        c = getchar(); 
        if(c == 45)
           sign = 45;
        for(; (c<48 || c>57); c = getchar());
        for(; c>47 && c<58 ; c = getchar()){
            i = (i<<1) + (i<<3) + c - 48;
        }
        printf("het ingevoerde getal is: %c%d\n",sign, i);

        return 0;
    }

I think this will work.

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

The problem in your code is that you are overwriting i every time you read a new character. You need to store the digit you read, and then add to it.

You should take care about not number characters :

while((ch=getchar()) != '\n')
   if(ch >= '0' && ch <= '9')
       i += 10* i + (ch - '0');

For the '-' or '+' at the begining you could store the first getchar(). A solution could be :

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

int main(void) {
   int i = 0;
   char ch,first_ch;

   printf("voer een getal in: ");

   ch = first_ch = getchar();
   while (ch != '\n') {
      if(ch >= '0' && ch <= '9')
         i = 10* i + (ch - '0');
      ch = getchar();
   }
   if(first_ch == '-')
      i *= -1;

   printf("het ingevoerde getal is: %d\n", i);
   return EXIT_SUCCESS;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top