从多行代码C ++中获取一个单词

时间:2013-10-13 21:29:51

标签: c++ vector

我有一个包含不同数量的单词/行的文本文件。一个例子是:

Hi

My name is Joe

How are you doing?

我想抓住用户输入的内容。所以,如果我搜索乔,那就可以了。不幸的是,我只能输出每一行而不是单词。我有一个矢量,每行都按行

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
            }

        }

现在line[1] = Hiline[2] = My name is Joe

我如何才能得到实际的字词?

1 个答案:

答案 0 :(得分:1)

operator>>使用空格作为分隔符,因此它已逐字逐字地读取输入:

#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] << ", ";
}

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

如果您要在此向量中查找特定关键字,只需以std::string对象的形式准备此关键字,您可以执行以下操作:

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
}