Search code examples
c++stringfile-iovectorformatted-input

Initializing a vector from a text file


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;
}

Solution

  • #include <fstream>
    #include <vector>
    #include <string>
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    using namespace std;
    
    int main()
    {
        vector<string> input;
        ifstream readFile("input.txt");
        copy(istream_iterator<string>(readFile), {}, back_inserter(input));
        cout << "Vector Size is now " << input.size();
    }
    

    Or, shorter:

    int main()
    {
        ifstream readFile("input.txt");
        cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
    }
    

    I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)