从多行代码 C++ 中获取一个词 [英] getting a word from multiple lines of code C++

查看:24
本文介绍了从多行代码 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?

我想获取用户输入的任何内容.所以如果我搜索Joe,它会得到那个.不幸的是,我只能输出每一行而不是单词.我有一个向量,它逐行保存这些中的每一个

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
            }

        }

所以现在line[1] = Hiline[2] = 我的名字是Joe.

我如何才能获得真正的单词?

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

推荐答案

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

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

输出:我的,名字,是,乔,怎么样,你,在做什么?,

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

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++ 中获取一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆