7

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.";

我想在以下位置添加一些代码:

    cout << "found: " << search << endl;

这将返回行号,后跟搜索的字符串。

4

2 回答 2

16

只需使用计数器变量来跟踪当前行号。每次你打电话给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;
    }
}

还...

while(!fileInput.eof())

应该

while(getline(fileInput, line))

如果在读取时发生错误eof将不会设置,因此您有一个无限循环。 std::getline返回一个流(您传递给它的流),它可以隐式转换为 a bool,它告诉您是否可以继续阅读,而不仅仅是在文件末尾时。

如果eof设置了,你仍然会退出循环,但是如果设置了,你也将退出,例如,bad有人在你阅读文件时删除了文件,等等。

于 2012-09-17T16:49:19.423 回答
5

已接受答案的修改版本。[对答案的评论作为建议会更好,但我还不能发表评论。]以下代码未经测试,但它应该可以工作

for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
    if (line.find(search) != string::npos) {
        cout << "found: " << search << "line: " << curLine << endl;
    }
}

for 循环使它稍微小一些(但可能更难阅读)。并且find中的 0应该是不必要的,因为 find 默认搜索整个字符串

于 2013-06-17T23:26:32.340 回答