查找包含指定单词的行(从文件中)
find lines (from a file) that contain a specified word
我不知道如何列出包含指定单词的行。我得到了一个包含文本行的.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)
}
相关文章:
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- C++文件包含多行
- CMake 如何强制third_party库将项目文件包含在当前项目源目录中?
- 是否可以将要"ShellExecute"的文件包含在 dll 中?如果是这样,"ShellExecute"中的文件位置应该是什么?
- C++ 逐行从文件(包含空格)读取数据
- 在 C++ 中,.h 文件包含文件但不起作用
- 生成的资源文件包含奇怪的包含文件
- 可变参数类的文件包含问题
- 为什么文件命令声明可执行文件包含"debug_info"
- 可以将标头文件包含在多个源文件中,而无需重复保护
- 为什么将.HPP文件包含在.h文件中
- Qt C++:将所有库文件包含在项目文件夹中
- 有条件地将文件包含在C++标头中
- 将多个原型文件包含在一个项目中会导致protobuf_AssignDescriptorsOnce()已经有一个主体
- 有没有办法将文件包含在C++中的所有项目文件中
- 将外部.asm文件包含到C++代码中
- 什么是"pch.h",为什么需要将其作为第一个头文件包含在内?
- 该头文件包含DirectX 12中的ThrowIfFailed()
- QT C :函数的多个定义当Header文件包含在MainWindow.h中时
- QT创建者错误地处理标头文件包含来自Directory