Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...