jpouliot
jpouliot

Reputation: 36

Read lines from file into string vector? C++

Ok, I'm a rookie at this and here is what I've been sitting here for a while scratching my head doing.

My goal is to read in a file from a command line argument and store the contents of the file in an array strings of which each element is a line from the file. I need the whole line including white spaces. And I need to cycle through the whole text file without knowing how large/small it is.

I'm fairly sure that key.eof() here is not right, but I've tried so many things now that I need to ask for help because I feel like I'm getting further and further from the solution.

ifstream key(argv[2]);
if (!key) // if file doesn't exist, EXIT
{
    cout << "Could not open the key file!\n";
    return EXIT_FAILURE;
}
else
{
    vector<string> lines;

    for (unsigned i = 0; i != key.eof(); ++i)
    {
        getline(key, lines[i]);
    }

    for (auto x : lines)
        cout << x;

If anyone could point me in the right direction, this is just the begging of what I have to do and if feel clueless. The goal is for me to be able to break down each line into a vector(or whatever I need) of chars INCLUDING white spaces.

Upvotes: 0

Views: 1006

Answers (2)

Galik
Galik

Reputation: 48605

I think you want something like this:

vector<string> lines;

string line;    
while(getline(key, line)) // keep going until eof or error
    lines.push_back(line); // add line to lines

Upvotes: 1

ruthless
ruthless

Reputation: 1140

To continuous read lines from file and keep it in array, I would do something like this using a while loop instead of a for loop.

int counter = 0;
while (getline(key, lines[counter]) {
    counter++;
}

Upvotes: 0

Related Questions