0

This is my first time using pointers, which is why my logic is probably very flawed. I am writing a program that sums up numbers in a string using atoi(). For example, sumNumbers("1 2 b asdsd 3 4) should be 10. Here is my program,

int sumString(char string[]) {
    char *ptr=string;
    int index = 0;
    int len = strlen(string);
    int sum = 0;
    while(index < len) {
        while (ptr[0] == ' ') {
            ptr++;
            index++;
            if (index == len) {
                return sum;
            } 
        }
        while (atoi(ptr) == 0) {
            ptr++;
            index++;
            if (index == len) {
                return sum;
            }
        }
        if (atoi(ptr) != 0) {
            sum += atoi(ptr);
            ptr++;
            index++;
            while (ptr[0] != ' ' || atoi(ptr) != 0 || ptr[0] == '\0') {
                ptr++;
                index++;
            }
        }
    }
    return sum;
}

My first conditional should get rid of all white spaces, my second should keep running for all letters, and my third should add up the value of atoi, keep going until a space or a letter, and then the loop should iterate again and the first two conditionals perform their tasks again. Unfortunately, this works for most cases except if I glue a letter to a number, like "18b5". This should return 23, but it returns 18 instead.

DrJessop
  • 462
  • 6
  • 26

2 Answers2

0

Apparently, my one problem was that my last while loop should have had && instead of || between the first two statements.

DrJessop
  • 462
  • 6
  • 26
0

The last loop should be changed to:

        while (ptr[0] != '\0' && atoi(ptr) != 0) {
            ptr++;
            index++;
        }
iamnoten
  • 231
  • 2
  • 7