Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string trouble in c

Tags:

c

string

The question is when I input a string with "sum" in begin and then compute the following number.

Input:

sum 10 20 

Output:

30

but my code is wrong,the output is 33 (the processing is 11+22=33) I think that the second while loop has wrong ,but I don't know how to revise.

I need any master help.

#include<stdio.h>

int main(){

    char a[100];

    while (gets(a))
    {
        if (a[0] == 's'&&a[1] == 'u'&&a[2] == 'm')
        {
            int i;
            int sum = 0;

            for (i = 2; a[i]; i++){
                if (a[i] == ' '){
                    i++;
                    int num = 0;
                    while (1){
                        num += num * 10 + (a[i] - '0');
                        i++;
                        if (a[i] == ' ' || a[i]=='\0') break;
                    }
                    sum += num;
                    i--;
                }
            }

            printf("%d", sum);
        }

    }
    return 0;
}
like image 706
bookgirl Avatar asked Dec 02 '25 14:12

bookgirl


1 Answers

num += num * 10 + (a[i] - '0');

should be

num = num * 10 + (a[i] - '0');
like image 96
mch Avatar answered Dec 04 '25 03:12

mch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!