0

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 ..."

  • 1
    What's wrong with `scanf(str, "%d %[^\n]", &dest_addr, message);` ? Do you really need each word as a separate string? – Lee Daniel Crocker Apr 25 '19 at 19:42
  • One alternate approach: [Use `strtol`](https://linux.die.net/man/3/strtol) instead of `sscanf`; 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). Avoids `sscanf` format string overhead as a bonus. – ShadowRanger Apr 25 '19 at 19:43
  • @LeeDanielCrocker: I suspect that's perfectly fine (seems like they don't want separate strings in the first place), but a lot of new C programmers don't notice the existence of the `[` conversion specifier. Definitely the simplest/shortest fix though. – ShadowRanger Apr 25 '19 at 19:45
  • @LeeDanielCrocker Oh, I should clarify that I dont need each word as a separate string. And as ShadowRanger implied, I am unfamiliar with the use of [ conversion – novicekiddo5131 Apr 25 '19 at 19:58
  • This link might be helpful mirror.fsf.org/pmon2000/2.x/src/lib/libc/scanf.c – caot Apr 25 '19 at 20:05
  • visit this link it maybe help you to solve your problem https://stackoverflow.com/questions/31536689/reading-combinations-of-string-and-integer-from-file-in-c – Tarek Rahman Apr 25 '19 at 20:10

0 Answers0