The string problem in c

The question is when I start typing a line with "sum" and then calculate the next number.

Input signal:

sum 10 20 

      

Output:

30

      

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

I need the help of a master.

#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;
}

      

+3


source to share


3 answers


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

      

it should be



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

      

+2


source


Here's a double counting happening:

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

      



For example, with the numbers "12", you have parsed 1, then add 12 to 1 to get 13. Change to:

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

      

+1


source


First of all, you must use fgets

is gets

deprecated. Second, I believe that you can reduce your code to half its current size by making it a disposable program, but you can still run it easily:

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

int main(int argc, char *argv[])
{
  if(argc != 3){
    printf("ERROR: Must input two integers!\n");
    return -1;
  }

  int first = strtol(argv[1], NULL, 0);
  int second = strtol(argv[2], NULL, 0);

  int sum = first + second;

  printf("%d\n", sum);

  return 0;
}

      

In this code, I am using argc

and argv

. This means that on the command line you can enter sum 10 20

and it will be passed in 10 and 20 as arguments. The second thing I use is strtol

this converts a string (10 and 20 start as strings) to long int

.

And you have to use GDB. this is Gnu DeBugger. Take a look.

0


source







All Articles