Home > Blockchain >  How to calculate the sum of all the numbers from a string like "10 5 6 31 3 45" in c
How to calculate the sum of all the numbers from a string like "10 5 6 31 3 45" in c

Time:11-11

I found this code but this sum all the digits but i want it to ad 31 not 3 1 Output : 28 Expected : 100

#include<stdio.h>  
int main()
{
    //Initializing variables.
    char str[100] = "10 5 6 31 3 45";
    int i,sum = 0;
    
    //Iterating each character through for loop.
    for (i= 0; str[i] != '\0'; i  )
    {
        if ((str[i] >= '0') && (str[i] <= '9'))  //Checking for numeric characters.
        {
            
            sum  = (str[i] - '0'); //Adding numeric characters.

        }
    }
    //Printing result.
    printf("Sum of all digits:\n%d", sum);
    return 0; 
}

CodePudding user response:

Since the delimiter apparently is the plus sign, you might utilize the "strkok" string function as noted in the following link strkok example.

Utilizing that method with your initial code resulted in the following code snippet.

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

int main()
{
    //Initializing variables.
    char str[100] = "10 5 6 31 3 45";
    int sum = 0;
    char *token;
    const char s[2] = " ";

    /* get the first token */
    token = strtok(str, s);

    /* walk through other tokens */
    while( token != NULL )
    {
        sum = sum   atoi(token);

        token = strtok(NULL, s);
    }
    //Printing result.
    printf("Sum of all numbers is: %d\n", sum);
    return 0;
}

Testing this code resulted in the following terminal output.

Sum of all numbers is: 100

Process returned 0 (0x0)   execution time : 0.035 s
Press any key to continue.

You might try this route to see if it meets the spirit of your project.

CodePudding user response:

We can iterate backwards through the string and add up all the digits, except a digit that we see after another digit is worth 10x more, because it is in a more significant position in the number.

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

int main() {
  char str[] = "10 5 6 31 3 45";

  unsigned int sum = 0;
  unsigned int digit_value = 1;

  unsigned int length = strlen(str);
  for (unsigned int i = 0; i < length; i  ) {
    char c = str[length - 1 - i];
    if (c == ' ') {
      digit_value = 1;
    }
    else if (c >= '0' && c <= '9') {
      sum  = digit_value * (c - '0');
      digit_value *= 10;
    }
  }

  printf("Sum: %d\n", sum);
}

This is a very specialized parser that is designed to just handle your specific type of problem. As soon as you add any complications (like minus signs), this parser would likely have to be re-written.

CodePudding user response:

Try this:

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

static void add_up(const char *in, char *out, size_t ndig)
{
  size_t dig = ndig;
  for (size_t i = strlen(in); i-- > 0; )
  {
    int ch = in[i];

    if (isdigit((unsigned char) ch)) {
      size_t j = dig;
      if (j == 0)
        goto overflow;
      out[--j]  = (ch - '0');
      while (j >= 1 && out[j] > '9') {
        out[j] -= 10;
        out[--j]  ;
      }
      if (out[j] > '9') {
      overflow:
        fputs("overflow\n", stderr);
        abort();
      }
      dig--;
    } else if (ch == ' ') {
      dig = ndig;
    }
  }
}

int main(int argc, char **argv)
{
  const char *self = argv[0] ? argv[0] : "unknown";
  char sum[] = "00000000";

  if (argc != 2) {
    fprintf(stderr, "%s: argument required\n", self);
    return EXIT_FAILURE;
  }

  add_up(argv[1], sum, sizeof sum - 1);
  puts(sum);
  return 0;
}
$ gcc -W -Wall -O2 strsum.c -o strsum
$ ./sumstr 1
00000001
$ ./sumstr 10
00000010
$ ./sumstr 1000
00001000
$ ./sumstr 10000
00010000
$ ./sumstr 100000
00100000
$ ./sumstr 1000000
01000000
$ ./sumstr 10000000
10000000
$ ./sumstr 100000000
overflow
Aborted (core dumped)
$ ./sumstr 1 2
00000003
$ ./sumstr 1 2 3
00000006
$ ./sumstr 1 2 3 4
00000010
$ ./sumstr 1 2 3 4 1000
00001010
$ ./sumstr 1 2 3 4 1000 13300
00014310
$ ./sumstr 1 2 3 4 1000 13300 1
00014311
$ ./sumstr 1 2 3 4 1000 13300 1 900000
00914311
$ ./sumstr 1 2 3 4 1000 13300 1 9000000
09014311
``
  •  Tags:  
  • c
  • Related