将文本文件插入到2D Vector c ++中

时间:2018-04-05 01:13:06

标签: c++ c++11

使用名为text.txt的文件作为命令行参数输入,如何创建文件对象并将文件加载到矢量>的2D矢量中?任何帮助都会很棒,谢谢! 这是我到目前为止只检查命令行的代码,但我不知道如何将它放入2d数组

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

int main(int argc, char* argv[]) {
    //1. Get filename from the command line
    if (argc <= 1) {
        cout << "Error: incorrect number of command line arguments\n"
            "Usage: allwords filename" << endl;
        return EXIT_FAILURE;
    }

    //Open the file to be read
    ifstream infile(argv[1]);
    if (!infile) {
        cout << "Error: failed to open <" << argv[1] << ">\n"
            "Check filename, path, or it doesn't exist.\n";
        return EXIT_FAILURE;
    }
    // ...
}

1 个答案:

答案 0 :(得分:0)

这可能适合你。它将创建一个向量,其中每个元素都是vector<char>格式的文件中的单词。

// The list
std::vector<std::vector<char>> text;
std::string word;
// Read entire file
while (infile >> word) {
    // Create the char vector and add it to main vector
    text.push_back(std::vector<char>(word.begin(), word.end()));
}

// Note: need to #include <algorithm> for count
int num_a = 0;
// Check each and every word for 'a'
for (auto word : text) {
    num_a += std::count(word.begin(), word.end(), 'a');
}
std::cout << "there are " << num_a << " a's" << std::endl;

// Vector for comparison
std::vector<char> a{ 'a' };
num_a = 0;
for (auto word : text) {
    num_a += word == a;
}
std::cout << "there word a appears " << count << " times" << std::endl;
相关问题