Initializing a vector from a text file

Deadly 提交于 2021-02-04 19:44:10

问题


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

回答1:


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



回答2:


#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 :)



来源:https://stackoverflow.com/questions/18947454/initializing-a-vector-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!