Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

vector - getting a word from multiple lines of code C++

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] == "
")
                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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

My name is Joe

How 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...