logo

Parsing a string of numbers in C

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { char str[] = "200, 22, 111 "; char* cursor = str; long int sum = 0; while (cursor != str + strlen(str)) { long int x = strtol(cursor, &cursor, 10); while (*cursor == ' ' || *cursor == ',') { cursor++; } sum += x; } printf("Sum is %ld\n", sum); return 0; }

Courses with this lesson