在文件中找到带有特定字符串的线路

Finding a number of a line with a specific string in a file

本文关键字:字符串 线路 文件      更新时间:2023-10-16

我希望我的程序返回有特定字符串的行数。整行应该是这个字符串。

我不知道为什么它总是返回整个文件的长度。

我的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <limits>
#include <windows.h>
using namespace std;

int main () {
int x;
x=0;
string filename, inputfilename, line;
ifstream inputfile;
while(!inputfile.is_open()) {
    cout << "Input filename: ";
    getline (cin, inputfilename);
    inputfile.open(inputfilename.c_str(),ios::in | ios::binary);
}
//string obj = "[I.LOVE.COOKIES]"; //Was like this
string obj = "[I.LOVE.COOKIES]r"; //Adding r solved the problem
while(getline(inputfile, line))
{
    if(line==obj)
    {
        return x;
    }
    else
    {
        x++;
    }
}
return 0;
}

打开文件时可能需要省略 ios::binary作为参数。

问题是,在Windows上,一行以两个字符rn结束。如果您以二进制模式打开文件,则std::getline将读取一条线,并包含托架返回r。这意味着您的字符串比较失败,因为字符串"[I.LOVE.COOKIES]"不会以r结束。