在文件中查找具有特定字符串的行号
Finding a number of a line with a specific string in a file
我希望我的程序 return 有特定字符串的行数。
整行应该是这个字符串。
我不知道为什么它总是 return整个文件的长度。
我的代码:
#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 上,一行以两个字符 \r\n
结束。如果以二进制模式打开文件,std::getline
将读取一行并包含回车 return \r
。这意味着您的字符串比较失败,因为字符串 "[I.LOVE.COOKIES]"
不以 \r
.
结尾
我希望我的程序 return 有特定字符串的行数。 整行应该是这个字符串。
我不知道为什么它总是 return整个文件的长度。
我的代码:
#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 上,一行以两个字符 \r\n
结束。如果以二进制模式打开文件,std::getline
将读取一行并包含回车 return \r
。这意味着您的字符串比较失败,因为字符串 "[I.LOVE.COOKIES]"
不以 \r
.