So I'm trying to teach myself a little C by writing a program that does some simple linear algebra manipulations on a matrix. The first hurdle is figuring out how to parse an input string that is a a series integers. I found the strtol function in the GNU C Library to be just what I was looking for. So, in order to get a feel for the function, I stole an example off the GNU manual that adds up a series of integers with spaces between them.
Here is the code I'm working on right now. All it does (or is _supposed_ to do) is take input from scanf, parse the integers, and spit out their sum.
This code lets me input the string, but ends in a seg fault after the carriage return. I'm not sure what to pass to the function - all this 'pointer to a pointer' stuff that the scanf function needs has me all confused.Code:#include <stdio.h> #include <stdlib.h> int errno; int sum_ints_from_string (char *string) { int sum = 0; while (1) { char *tail; int next; /* Skip whitespace by hand, to detect the end. */ while (isspace (*string)) string++; if (*string == 0) break; /* There is more nonwhitespace, */ /* so it ought to be another number. */ errno = 0; /* Parse it. */ next = strtol (string, &tail, 0); /* Add it in, if not overflow. */ if (errno) printf ("Overflow\n"); else sum += next; /* Advance past it. */ string = tail; } return sum; } int main() { int result; char *p; scanf("%[0-9 ]",&p); result = sum_ints_from_string(p); printf("%d\n",result); return 0; }
Thanks for helping a confused newb![]()



LinkBack URL
About LinkBacks





