Question

I have a .txt file which I'm trying to gather data from, that can then be used within variables within my code to be used in other functions.

Here's an example of my text file:

0 10 a namez 1 0
0 11 b namea 1 1
1 12 c nameb 1 1
2 13 d namec 0 1
3 14 e named 1 1

So my file will not always be the same number of lines, but always the same number of variables per line.

I currently have this, to firstly get the length of the file and then change the amount of rows within the array:

int FileLength()
{

    int linecount = 0;
    string line;
    ifstream WorkingFile("file.txt");
    while(getline(WorkingFile, line))
    {
        ++linecount;
    }
    return linecount;
}
int main()
{
    string FileTable [FileLength()][6];
}

Firstly I don't know if the above code is correct or how I can add the values from my file into my FileTable array.

Once I have my FileTable array with all the file data in it, I then want to be able to use this in other functions.

I've been able to do:

if(FileTable[2][0] = 1)
{
    cout << "The third name is: " << FileTable[2][3] << endl;
}

I understand my code may not make sense here but I hope it demonstrates what I'm attempting to do.

I have to do this for a larger text file and all the 6 variables per line relate to be input to a function.

Was it helpful?

Solution

Hold each line in its own object, this is much clearer:

struct Entry
{
    std::array<std::string, 6> items;  // or a vector
};

In main:

std::vector<Entry> file_table( FileLength() );

Note that it is a waste of time to read the whole file first in order to find the number of entries. You could just start with an empty vector, and push in each entry as you read it.

Your access code:

if( file_table.size() > 2 && file_table[2].items[0] == "1" )
{
    cout << "The third name is: " << FileTable[2].items[2] << endl;
}

I would actually recommend giving the members of Entry names, instead of just having an array of 6 of them. That would make your code more readable. (Unless you really need to iterate over them, in which case you can use an enum for the indices).

You could define an operator[] overload for Entry if you don't like the .items bit.

OTHER TIPS

since the number of lines is dynamic I suggest to use vector instead of array. you can push back your data to the vector line by line until you read eof. also try to study about OOP a little , it would make your code more understandable.

take look at these:

http://www.cplusplus.com/reference/vector/vector/

http://www.geeksforgeeks.org/eof-and-feof-in-c/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top