简体   繁体   中英

Fill vector of string vectors from input file

I would really appreciate the help here. I need to fill a vector of string vectors using text from an input file. I really have no idea how to start off.

I have something like this in a function to read in the words, but I keep getting a compiler error saying I can't push back a string, so I know I'm on the wrong track. Any help would be very much appreciated.

ifstream input(filename);

for (int i = 0; i < 4; i++)
{

  for (int j = 0; j < 4; j++)
  {
    string line;
    getline(input, line);
    stringstream temp(line);
    string tempWord;
    temp >> tempWord;
    words[i][j].push_back(tempWord);
  }

If words is a vector<vector<string>> then words[i][j] is accessing a string . What you might looking to do is is words[i][j] = tempWord; . string also has a function .push_back() but takes a char which is why the error you are getting is that you can't push_back a string, the push_back() for string s is for appending characters to the string. Also depending on how you declared words , if you didn't give sizes, words[i][j] might be accessing out of range and a better approach would be to do words[i].push_back(tempWord) . Also looking at your for loops I'm not sure of your intent for which words from the file you want but currently as your code is, it will read in the first 16 lines of the file and place the first "word" from each into your words object. If your intent is instead to have a vector of vectors of string where each subvector is the words in a line then something like below might be better.

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


int main(int argc, char* argv[])
{
    std::string filename = "testfile.txt";
    std::ifstream input(filename.c_str());
    if(!input){
        std::cerr << "Error in opening file: " << filename << "\n";
        return 1;
    }
    std::vector<std::vector<std::string> > words;
    std::string line;

    while(std::getline(input, line)){
        std::stringstream ss;
        ss << line;
        std::vector<std::string> row;
        while (!ss.eof()) {
            std::string tempStr;
            ss >> tempStr;
            row.push_back(tempStr);
        }
        words.push_back(row);
    }
    //... then do something with words here
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM