c++ - 查找包含指定单词的行(从文件中)
问题描述
我不知道如何列出包含指定单词的行。为我提供了一个包含文本行的 .txt 文件。
到目前为止,我已经走了这么远,但是我的代码正在输出那里的行数。目前,这是我认为有意义的解决方案:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
void searchFile(istream& file, string& word) {
string line;
int lineCount = 0;
while(getline(file, line)) {
lineCount++;
if (line.find(word)) {
cout << lineCount;
}
}
}
int main() {
ifstream infile("words.txt");
string word = "test";
searchFile(infile, word);
}
但是,这段代码根本没有得到我期望的结果。输出应该只是简单地说明哪些行上有指定的单词。
解决方案
因此,从评论中总结解决方案。这只是关于std::string
的find
成员函数。它不返回与布尔值兼容的任何内容,如果找到则返回索引,或者std::string::npos
如果未找到,则返回一个特殊常量。
所以用传统方式调用它if (line.find(word))
是错误的,而是应该这样检查:
if (line.find(word) != std::string::npos) {
std::cout << "Found the string at line: " << lineCount << "\n";
} else {
// String not found (of course this else block could be omitted)
}
推荐阅读
- laravel-5 - Laravel 会话消息作为 toastr 通知
- javascript - 混合 android 应用程序在构建后无法正常工作
- angular - Angular:绑定到服务的可观察属性 - >值不会更新
- python - Linux 和 Windows 在 Python 寻址 CSV 文件中的区别
- node.js - npm install angular-cli 不工作
- sparql - 我想在基于 Lahman Baseball 数据库的 sparql 中进行选择查询和连接两个数据集
- android - 使用 Flutter 时我有哪些存储数据的选项?(iOS 和安卓)
- javascript - TypeError: _this.state.answers.push 不是 React 函数
- c - 过度使用 realloc
- python - 使用步骤构造迭代器