从文本文件初始化矢量

Jac*_*ses 2 c++ string file-io vector formatted-input

我正在尝试编写一个可以读入文本文件的程序,并将其中的每个单词存储为字符串类型向量中的条目.我确信我这样做是非常错误的,但是自从我试图做到这一点以来,我已经忘记了它是如何完成的.任何帮助是极大的赞赏.提前致谢.

码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Lih*_*ihO 6

许多可能的方法之一是一个简单的方法:

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

std::string word;
while (file >> word) {
    words.push_back(word);
}
Run Code Online (Sandbox Code Playgroud)

运算符>>只处理被读取的空格(包括换行符)划分的单词.


如果您要按行读取它,您可能还需要显式处理空行:

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);
}
Run Code Online (Sandbox Code Playgroud)