I want to read lines from a text file and store the information in three variables. For example, if the line from a file is
A Tale of Two Cities Charles Dickens 1859
I want to store this into two char arrays and one int variable. So, I want to extract the following information from the line. There is no delimiter like comma or hyphen in the line.
title[] = "A Tale of Two Cities"
author[] = "Charles Dickens"
year = 1859
How can this be done in C? Problem is that title could have variable number of words in it. Same for the author. If there was fixed number of words in either of them, then problem is easy. So, what is the desirable solution here ?
>Solution :
If these files have a predefined file format, your best bet is to find out what that format is; only then will you be able to even begin writing a program that reads the files.
If, on the other hand, these files are something you personally made up, then the format is completely up to you; but whatever format you choose, you have to ensure that each file conforms to it. After you have decided this format, you can begin to design a parser that reads the files.
If you do not know in advance the number of spaces between fields, then you have to use a delimiter, which is a symbol that definitively marks the end of that field. For example:
A Tale of Two Cities Charles Dickens 1859
Could be:
A Tale of Two Cities |Charles Dickens| 1859|
Where the pipe symbol is the delimiter. Then, you can separate each field by looking for the pipe, ignoring leading and trailing spaces afterwards.