I have a programming assignment which I must complete and I need help starting it. We can't talk about code with the professor or the TA so I thought I'd come here to try and ask.

Pretty much were going to be given a text file. This text file will have an undefined number lines, but it will be only 4 ints per line separated by a space or tab.

I need to be able to read the file 1 line at a time and extract these four ints on the line and separate them into different variables. userId, time, from, to.

That's where I have my problem on because I don't know how to do that exactly. The time int is the most important because it must be compared with the time of the program.

So it would have to be something like if the time on the line matches the time on the program then I have to create a thread. The thread can only be created if the time matches so I can't read the whole file and create threads right away.

I know you can't give out code and that is not what I want. I want like a direction on how to begin.

Thanks.

Recommended Answers

All 3 Replies

use fgets() to read a line, then for each line you can use strtok() to tokenize it, then atol() to convert from char* to int.

Another way is to use strtol() in a loop. Example

int main()
{
    char line[] = "12 23 34 45";
    char* ptr;
    int n1[4];
    int i;
    i = 0;
    ptr = line;
    while(*ptr != '\0' && (n1[i] = strtol(ptr,&ptr,10)) < LONG_MAX )
    {
        printf("%d\n", n1[i]);
        i++;
    }
}

Thank you for your reply, but the numbers in the txt file is unknown. There can be 5 rows til 100, but there will always be four ints in a line. I want to use fscanf to read the ints using %d as the format. But my problem comes in I need to take note of each int and separate them. How can I make the program so that it grabs the 1st int and says your the 'userid', grabs the 2nd int and says your the 'time', grab the 3rd int and say your 'from', and lastly grab the 4th and say your 'to'. Then repeat for each other line.

I already told you with the code I posted above. It does exactly what you are asking. I just put the numbers in an array of integers rather than in individual variables. Just put the code I gave you in a loop that uses fgets() to read the file one line at a time, so that you know the begenning of each line.

Or if you know there will always be 4 numbers on each line and that it will never ever be anything else

int userID;
int time;
int from;
int to;
FILE*fp = fopen("filename.txt","r");
while( fscanf(fp,"%d%d%d%d", &userID,&time,&from,&to) > 0)
{
   // do something with the data
}
fclose(fp);
commented: Was very nice and helpful +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.