Question

I have an input text file that has disparate information on each line but I need to be able to quickly select a specific word from a particular line a couple hundred times so i need a vector of string vectors.

I have 2 starting points but don't know how to proceed on either.

std::vector<std::string> lines;
std::string line;
while ( std::getline(input, line) ) {
    if ( !line.empty() )
        lines.push_back(line);
}

which separates it into lines

or

std::string word;
while (in_str >> word ) {
    input.push_back(word);
}

which separates it into words

Was it helpful?

Solution

You may combine two approaches :-)

First you get the whole line with getline, and then consider that line a source of std::istringstream (which essentially is a usual istream) and split the input into words).

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

int main(void) {
    std::vector<std::vector<std::string> > lines;
    std::string line;
    while ( std::getline(std::cin, line) ) {
        if ( !line.empty() ) {
            std::vector<std::string> words;
            std::string word;
            std::istringstream is(line);
            while (is >> word)
                words.push_back(word);
            lines.push_back(words);
        }
    }
    std::cout << "The word at line 3, pos 2 is \"" << lines[2][1] << '"' << std::endl;
    return 0;
}

which gives me the following:

abc def gdf
qwe asd zxc
qaz wsx edc
The word at line 3, pos 2 is "wsx"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top