Search code examples
cwhile-loopfgets

Finding sum of ints in a string


I need to output the sum of the numbers that are inside of a sentence. For example :

  • input: abc3x casa2 y34zq
  • output : 3+2+3+4 = 12

I need to read all the sentences include the space to do this, but my loop with getchar doesn't work. Can help me to find the problem?

int main() {

    int i = 0;
    int somma = 0;
    char s[MAX];

    printf("inserisci la stringa : ");
    scanf("%s",s);

        while((s[i] = getchar()) != '\n'){
            i++;
            if(s[i]>'0' && s[i]<'9'){
            somma+= (int)s[i]-(int)'0';
        }
    }
    printf("la somma è = %d", somma);
}

I don’t have to use getchar. I would prefer to use fgets because I know that fgets can read the entire line including the space.


Solution

  • There are two ways to solve your problem.

    1. Get entire string in one go from user

    To read entire string, you can use scanf as you are using it. It will store entire string in array (s in your case) and then you can parse this array and peform operations as you are doing. Here limitation would be length of string. You can accept string of the MAX size only as your array is of that much size. If you are okay with this, then your code is correct. All you need to do is remove that getChar() from while.

    1. Read one character at a time.

    Alternatively, you can read one character at a time from user and immediately perform operations on that character. In that case, you don't need to declare array. One character variable is sufficient and you can go on accepting data from user. In this case, discard the scanf() and in your while(), accept getChar() output in one character and perform your operation.

    P.S. There's one small bug in your while() which will give you incorrect result in few cases.