First off, I'm a beginner in C and programming in general. What I want to do in this case is to read a small story from a text file, and store the int and string that I get from it (similar to sscanf()). Here is the content of the text file:
8 Those be rubies, fairy favours;
256 In those freckles live their savours;
128 I must go seek some dewdrops here,
4 And hang a pearl in every cowslip's ear.
64 QUIT
I've considered using sscanf, however the amount of strings here are not consistent, so I cannot use sscanf(buf, "%d %s %s ...", &n, s). Here is a snippet from what I have:
char str[1000], message[1000];
int dest_addr;
while(fgets(str, 1000, f) != NULL){
sscanf(str, "%d %s", &dest_addr, message);
printf("%d %s\n", dest_addr, message);
}
I need to store the int in the beginning of a line in int dest_addr, and the following string in message[].
Edit: E.g. need to store "Those be rubies, fairy favours" in message[], print the entire line, then continue to the next line which is "256 In those ..."
scanf(str, "%d %[^\n]", &dest_addr, message);? Do you really need each word as a separate string?strtolinstead ofsscanf; the value filled in in the second argument tells you where it stopped parsing the number, so you can pull the rest of the string from there (after skipping whitespace, if desired). Avoidssscanfformat string overhead as a bonus.[conversion specifier. Definitely the simplest/shortest fix though.