C++ searching text file for a particular string and returning the line number where that string is on(C++ 在文本文件中搜索特定字符串并返回该字符串所在的行号)
问题描述
c++ 中是否有特定的函数可以返回我要查找的特定字符串的行号?
Is there a particular function in c++ that can return the line number of a particular string i want to find?
ifstream fileInput;
int offset;
string line;
char* search = "a"; // test variable to search in file
// open file to search
fileInput.open(cfilename.c_str());
if(fileInput.is_open()) {
while(!fileInput.eof()) {
getline(fileInput, line);
if ((offset = line.find(search, 0)) != string::npos) {
cout << "found: " << search << endl;
}
}
fileInput.close();
}
else cout << "Unable to open file.";
我想在以下位置添加一些代码:
I want to add some codes at:
cout << "found: " << search << endl;
这将返回行号,后跟搜索的字符串.
That will return the line number followed by the string that was searched.
推荐答案
只需使用计数器变量来跟踪当前行号.每次您调用 getline
时,您...读取一行...所以在那之后增加变量.
Just use a counter variable to keep track of the current line number. Each time you call getline
you... read a line... so just increment the variable after that.
unsigned int curLine = 0;
while(getline(fileInput, line)) { // I changed this, see below
curLine++;
if (line.find(search, 0) != string::npos) {
cout << "found: " << search << "line: " << curLine << endl;
}
}
还有……
while(!fileInput.eof())
应该是
while(getline(fileInput, line))
如果读取时发生错误 eof
将不会被设置,所以你有一个无限循环.std::getline
返回一个流(你传递给它的流),它可以隐式转换为 bool
,它告诉你是否可以继续阅读,而不仅仅是如果你在文件的末尾.
If an error occurs while reading eof
will not be set, so you have an infinite loop. std::getline
returns a stream (the stream you passed it) which can be implicitly converted to a bool
, which tells you if you can continue to read, not only if you are at the end of the file.
如果设置了eof
,你仍然会退出循环,但是如果设置了bad
,你也会退出,当你阅读时有人删除了文件它等等.
If eof
is set you will still exit the loop, but you will also exit if, for example, bad
is set, someone deletes the file while you are reading it, etc.
这篇关于C++ 在文本文件中搜索特定字符串并返回该字符串所在的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 在文本文件中搜索特定字符串并返回该字符串所在的行号
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01