Initializing a vector from a text file

Jacob Moses picture Jacob Moses · Sep 22, 2013 · Viewed 9.8k times · Source

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.

Code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> input;
    ifstream readFile;

    vector<string>::iterator it;
    it = input.begin();

    readFile.open("input.txt");

    for (it; ; it++)
    {
        char cWord[20];
        string word;

        word = readFile.get(*cWord, 20, '\n');

        if (!readFile.eof())
        {
            input.push_back(word);
        }
        else
            break;
    }

    cout << "Vector Size is now %d" << input.size();

    return 0;
}

Answer

LihO picture LihO · Sep 22, 2013

One of the many possible ways is a simple:

std::vector<std::string> words;
std::ifstream file("input.txt");

std::string word;
while (file >> word) {
    words.push_back(word);
}

operator >> takes care of only words divided by whitespaces (including new-lines) being read.


And in case you would be reading it by lines, you might also need to explicitly handle empty lines:

std::vector<std::string> lines;
std::ifstream file("input.txt");

std::string line;
while ( std::getline(file, line) ) {
    if ( !line.empty() )
        lines.push_back(line);
}