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

6
  • 1
    What's wrong with scanf(str, "%d %[^\n]", &dest_addr, message); ? Do you really need each word as a separate string? Commented Apr 25, 2019 at 19:42
  • One alternate approach: Use 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. Commented Apr 25, 2019 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. Commented Apr 25, 2019 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 Commented Apr 25, 2019 at 19:58
  • This link might be helpful mirror.fsf.org/pmon2000/2.x/src/lib/libc/scanf.c Commented Apr 25, 2019 at 20:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.