我希望我的程序返回其中存在特定字符串的行数。 整行应该是这个字符串。在文件中查找具有特定字符串的行数
我不知道为什么它总是返回整个文件的长度。
我的代码:
#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;
}
因为该文件不包含搜索字符串,并且显示的代码在这种情况下表现出未定义的行为,所以通过从'main()'返回而没有值返回。此外,这个程序只能处理非常小的文件,因为程序的返回码仅限于7位。换句话说:废弃这一切,并从头开始重写。 –
如果你正在阅读文本,我会放弃ios :: binary ... – Baldrick
@SamVarshavchik为什么从主体返回没有价值的UB? – user463035818