C Help - Reading from file.

Hi guys,

So I have this text file that I am trying to read from and store the values of each line in multiple variables.

Let's say my text file contains


AXSYZ3482 Tom 100 112


and my code below here works fine when the lines in the text file is separated by spaces.


while (fscanf(fp, "%s %s %d %d\n", userID, name, &startLoc, &endLoc) != EOF) {
printf("%s %s %d %d\n", userID, name, startLoc, endLoc);
}


But let's say my file was to look like this instead.


AXSYZ3482:Tom:100:112


But if i try this below...



while (fscanf(fp, "%s:%s:%d:%d\n", userID, name, &startLoc, &endLoc) != EOF) {
printf("%s %s %d %d\n", userID, name, startLoc, endLoc);
}


It seem to store the entire line in userID including the ":". I want to ignore the ":"'s and store everything in between in respective varibles in the order specified above.

So first string in userID, then ignore the :, then second string in name, and ignore the next :, and so forth.

Any idea how I can accomplish this? Any help would be greatly appreciated.

Thanks in advance. :)

Cheers
First, never use %s, always specify the size limit (as in "%123s" for a buffer of 124 bytes). Also, compare the result of fscanf() with the expected number, not with EOF (otherwise you'd never know if it failed halfway through)

As for your problem, use [^:] to scan all characters up until :, like so

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
int main()
{
    char userID[20];
    char name[20];
    int startLoc;
    int endLoc;

    FILE* fp = fopen("test.txt", "r");

    while (fp && fscanf(fp, "%19[^:]:%19[^:]:%d:%d ",
                       userID, name, &startLoc, &endLoc) == 4)
    {
        printf("%s %s %d %d\n", userID, name, startLoc, endLoc);
    }
}

Thanks Cubbi, appreciate it :)
Topic archived. No new replies allowed.