I am trying to create a function in C that divides a string based on two spaces:
char *string = "10234540234 the";
I want get_weight() to return
10234540234
Here is how my function is defined
long get_weight(char *string) {
long length = strlen(string);
printf("%c \n", string[11]);
char *number[200];
int count = 0;
for (int i = 0; i < length; i++) {
if (string[i] == " " && string[i+1] == " ") {
break;
} else {
number[count] = string[i];
count++;
}
}
return atol(number);
}
It goes into an infinite loop, and I am not sure why...
\0at the end ofnumberreturn atol(number);should be flagging a compiler warning. The function requiresconst char *, you're passing anything-but.atol("123 xyz")would also return 123?long get_weight(char *string) { return atol(string); }. becauseatoiwill stop at the first wrong character. For better error checking I suggest to usestrtolinstead ofatol.sscanf?