C++ 在文本文件中搜索特定字符串并返回该字符串所在的行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12463750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ searching text file for a particular string and returning the line number where that string is on
提问by John Marston
Is there a particular function in c++ that can return the line number of a particular string i want to find?
C++ 中是否有一个特定的函数可以返回我想要查找的特定字符串的行号?
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.
这将返回行号,后跟搜索的字符串。
回答by Ed S.
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.
只需使用计数器变量来跟踪当前行号。每次你打电话给getline
你……读一行……所以在那之后增加变量。
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;
}
}
Also...
还...
while(!fileInput.eof())
while(!fileInput.eof())
should be
应该
while(getline(fileInput, line))
while(getline(fileInput, line))
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
将不会设置,因此您将陷入无限循环。 std::getline
返回一个流(你传递给它的流),它可以隐式转换为 a bool
,它告诉你是否可以继续阅读,而不仅仅是当你在文件末尾时。
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.
如果eof
已设置,您仍将退出循环,但如果例如bad
已设置、有人在您阅读文件时删除文件等,您也会退出。
回答by studiou
A modified version of the accepted answer. [A comment on the answer as a suggestion would have been preferable but I can't comment yet.] The following code is untested but it should work
已接受答案的修改版本。[对答案的评论作为建议会更可取,但我还不能评论。] 以下代码未经测试,但应该可以工作
for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
if (line.find(search) != string::npos) {
cout << "found: " << search << "line: " << curLine << endl;
}
}
for loop makes it slightly smaller (but perhaps harder to read). And 0 in findshould be unnecessary because find by default searches the whole string
for 循环使它稍微变小(但可能更难阅读)。而find 中的0应该是不必要的,因为 find 默认搜索整个字符串