getting a word from multiple lines of code C++

2019-09-19 09:50发布

问题:

I have a text file with a varied number of words/lines. An example would be:

Hi

My name is Joe

How are you doing?

I'm wanting to grab whatever the user inputs. So if I search for Joe, it'll get that. Unfortunately, I am only able to output each line instead of the word. I have a vector that is holding each one of these line by line

vector<string> line;
string search_word;
int linenumber=1;
    while (cin >> search_word)
    {
        for (int x=0; x < line.size(); x++)
        {
            if (line[x] == "\n")
                linenumber++;
            for (int s=0; s < line[x].size(); s++)
            {
                cout << line[x]; //This is outputting the letter instead of what I want which is the word. Once I have that I can do a comparison operator between search_word and this
            }

        }

So right now line[1] = Hi, line[2] = My name is Joe.

How would I get it to where I can get the actual word?

回答1:

operator>> uses whitespaces as separators, thus it is reading the input word by word already:

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

int main() {
    std::istringstream in("Hi\n\nMy name is Joe\n\nHow are you doing?");

    std::string word;
    std::vector<std::string> words;
    while (in >> word) {
        words.push_back(word);
    }

    for (size_t i = 0; i < words.size(); ++i)
        std::cout << words[i] << ", ";
}

outputs: Hi, My, name, is, Joe, How, are, you, doing?,

In case you are going to look for specific keywords within this vector, just prepare this keyword in form of std::string object and you might do something like:

std::string keyword;
...
std::vector<std::string>::iterator i;
i = std::find(words.begin(), words.end(), keyword);
if (i != words.end()) {
    // TODO: keyword found
}
else {
    // TODO: keyword not found
}


标签: c++ vector