I want to get the weight and the object in a list string( in this example I want to get the integer 501 and the string "kg bag of sugar". But I don't know-how may string after the integer. but I do know how many spaces before and after the integer (that is why I do +3 since there are 2 spaces before integer and 1 space at the end). I got a segmentation fault in my code.
Here is an example of what I am trying to do.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* get the weight and the object */
int main(void) {
char line[50] = " 501 kg bag of sugar"; //we don't know how many char after integer
char afterint[50];
long int weight, weight2;
int lenofint;
sscanf(line, "%ld", &weight);
weight2 = weight;
while (weight2 != 0) {
weight2 = weight2 / 10;
lenofint++;
}
afterint[0] = line[lenofint + 3]; // +3 since there are 2 spaces before integer and 1 space at the end
//printf("%c", afterint);
for (int j = 1; j < (strlen(line) - lenofint - 3); j++) {
afterint[j] = afterint[j] + line[j + lenofint + 3];
}
printf("%s", afterint);
}