从多行代码中获取单词C++
getting a word from multiple lines of code C++
我有一个文本文件,其中包含不同数量的单词/行。一个例子是:
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] = Hi
,line[2] = My name is Joe
.
怎样才能得到我能得到实际单词的地方?
operator>>
使用空格作为分隔符,因此它已经逐字读取输入:
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::istringstream in("HinnMy name is JoennHow 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
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何在 c++ 中从文本文件中获取特定单词?
- 如何获取句子中单词的第一个字母*没有*指针,引用等
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 用于获取以元音和辅音开头的单词数量的程序返回错误的答案
- 如何在 c++ 中从文本文件的正文中获取特定的单词和行
- QTEXTEDIT:在鼠标指针下获取单词
- 从两个单词之间获取字符串
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- C++如何在两个单词之间获取字符串/字符
- 获取字符串的第一个单词并从实际字符串中删除该单词
- 从多行代码中获取单词C++
- 从vector和unordered_map中获取三个出现次数最多的单词及其计数值
- 使用c++获取字符串中每个单词的第一个字母
- 获取字符'='之前的所有标准::字符串或第一个单词
- 从字符串中获取一个单词,对其进行更改,然后将其放回正确的位置
- 获取字符串输入以创建单词
- 这个算法获取所有单词梯的时间复杂度是多少?
- 在c++中从字符串中获取每个单独的单词