Search code examples
c++arraysfilefile-iofstream

Reading information from a text file and properly storing it in arrays, int


I would like to have a piece of C++ code that reads from a text file and saves the information in some variables, arrays...

For example, let's say we have a file Numbers.txt, which contains 4 integers. An example code that I found so far ( and does not do the trick for me ) looks like this :

string weight, height, width, depth;
ifstream MyFile("Numbers.txt");
MyFile >> weight;
MyFile >> height;
MyFile >> width;
MyFile >> depth;

But it only reads single pieces of data, separated by an empty space.

I would like code to be able to read several pieces of data that can be in a same row. To clarify, that's an example of how a text file format would look like...

FileName
ProjectName
Names
IDs

and en example of actual content of a text file ...

// SomeData.txt 
FileName: SomeData.txt
ProjectName: Second Attempt // should be able to read with spaces too, and save in a string as "Second Attempt" 
Names: John, Frank, Mike // I guess it could be without commas too
IDs: 42, 505, 1591, 4358, 12, 743

So the main problem is for the program to skip to next lines while reading, and ignoring "keywords" like "Names:", "IDs"... and at the same time be ready to read as many entries as there are in a line, even if there is no information in advance of how many there would be.

The information just read would best be saved as such:

FileName -> string
ProjectName -> string
Names -> array of strings
IDs -> array of integers

How would an example of such code look like ?


Solution

  • My answer is incomplete but here's an overview of how I would go about this:

    When you are using an ifstream you can grab the whole line at once using a function called getline and store it in a char array.

    You could then use a function such as strtok to split that line up, as I notice that the data comes after a : character.

    At this point you could have a switch statement depending on the string before the :, and process your data appropriately. For example if you have IDs then use atoi to convert them to ints and store them in arrays etc.