0

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.

jpouliot
  • 36
  • 4
  • 1
    You must be joking. There are thousands of duplicates on this website. Did you make *any* effort searching for this? – Kerrek SB Jul 11 '14 at 01:53
  • Here is a [particularly edifying post](http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line/2292517). – Kerrek SB Jul 11 '14 at 01:56
  • [Quick and dirty demo](http://ideone.com/o8cOac) – Kerrek SB Jul 11 '14 at 02:02

2 Answers2

1

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
Galik
  • 47,303
  • 4
  • 80
  • 117
  • `for(string line; getline(key, line); lines.push_back(line));` is nicer IMHO. (or `emplace_back(std:move(line))` ;)) – melak47 Jul 11 '14 at 16:59
0

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++;
}
ruthless
  • 1,090
  • 4
  • 16
  • 36