Bramble
Bramble

Reputation: 1395

Get file info into variables?

What is the best way to get this info from a file for each line?

the text file looks like this

1 E  
1 P  
1 C  
2 E a  
5 E P C  

So i need to get the info from line 1(1 E) put 1 into a variable and then E into another. The same for the rest of the lines, but some have a different number of elements which I dont understand how to do.

Upvotes: 0

Views: 488

Answers (3)

Khaled Alshaya
Khaled Alshaya

Reputation: 96879

A quick/dirty solution.

#include <fstream>
#include <vector>
#include <string>
#include <sstream>

int main()
{
    using namespace std;

    typedef pair<size_t, vector<string> > infoPair;
    typedef vector<infoPair > infoVector;

    ifstream inputFile("test.txt");
    size_t lineNumber = 1;
    infoVector info;
    string line;

    while(getline(inputFile, line))
    {
        stringstream extractor(line);
        vector<string> symbols;
        string symbol;

        while(extractor >> symbol)
        {
            symbols.push_back(symbol);
        }

        info.push_back(infoPair(lineNumber, symbols));
        lineNumber++;
    }

    return 0;
}

Upvotes: 1

sepp2k
sepp2k

Reputation: 370172

You can use filestream >> intvariable; to read the integer at the beginning of the line. You can then use getline to read the rest of the line into a string and then maybe split that into an array or do whatever else you want to do with it. You weren't very specific as to what exactly you want to do.

Upvotes: 0

Glen
Glen

Reputation: 22290

You'll probably need a vector of vectors.

std::vector<std::vector<std::string> > info;

The inner vector contains each word in a line

The outer vector contains each line.

Read each line in the file, tokenise the line, add each token to the inner vector, add the vector for the words to the vector for each line

Sounds like a homework question so I'm not going to post the code showing how to read a file, or tokenise the string

Upvotes: 1

Related Questions