Diablo Diablo - 1 month ago 8
C Question

Reading a .txt File and getting words/integers as strings

I have a .txt file:

apple 123 12 1 7 3 222
danger 1234 11 223 44 87 65
what 2322 6567 54
its 9128 88 66 12 12


EDIT:
New Question. I tried using fgets to get 1 line at a time with a while function then using sscanf to go through the line and making each word/integer into its own string. So in theory first term_in should be apple then 123 then 12 and so forth. Ok now it compiles but it doesnt work. Nothing is printing out.

int offset;
char line[1000];
FILE *fp;
char term_in[1000];
fp = fopen(argv[1], "r");

while (fgets(line, sizeof(line), fp) != NULL) {
char *data = line;
while (sscanf(line, " %s%n", term_in, &offset) == 1) {
data += offset;
printf("%s", term_in);
}
}

Answer

You're getting close. Here's a minor adaptation — an MCVE (Minimal, Complete, Verifiable Example) that works:

#include <stdio.h>

int main(void)
{
    int offset;
    char line[1000];
    FILE *fp = stdin;   // Important but simple change
    char term_in[1000];

    while (fgets(line, sizeof(line), fp) != NULL) {
        char *data = line;
        while (sscanf(data, "%s%n", term_in, &offset) == 1) { // Changes
            data += offset;
            printf("[%s]\n", term_in);  // Trivial change
        }
    }

    return 0;
}

Here's an example run (it was called rl59.c and compiled to rl59):

$  rl59 <<< 'Once upon a time, there was a country that held nice, civilized presidential elections.'
[Once]
[upon]
[a]
[time,]
[there]
[was]
[a]
[country]
[that]
[held]
[nice,]
[civilized]
[presidential]
[elections.]
$

And given a multi-line input file:

So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots

The output was:

[So]
[she]
[went]
[into]
[the]
[garden]
[to]
[cut]
[a]
[cabbage-leaf]
[to]
[make]
[an]
[apple-pie]
[and]
[at]
[the]
[same]
[time]
[a]
[great]
[she-bear]
[coming]
[down]
[the]
[street]
[pops]
[its]
[head]
[into]
[the]
[shop]
[What]
[no]
[soap]
[So]
[he]
[died]
[and]
[she]
[very]
[imprudently]
[married]
[the]
[Barber]
[and]
[there]
[were]
[present]
[the]
[Picninnies]
[and]
[the]
[Joblillies]
[and]
[the]
[Garyulies]
[and]
[the]
[great]
[Panjandrum]
[himself]
[with]
[the]
[little]
[round]
[button]
[at]
[top]
[and]
[they]
[all]
[fell]
[to]
[playing]
[the]
[game]
[of]
[catch-as-catch-can]
[till]
[the]
[gunpowder]
[ran]
[out]
[at]
[the]
[heels]
[of]
[their]
[boots]
Comments