更新时间:2023-11-25 20:47:04
while循环应测试ifstream是否为eof或使用good()时出错。 getline只返回文件流而不是布尔表达式。
The while loop should test if the ifstream is at eof or an error using good(). getline only returns the file stream not a boolean expression.
int main()
{
string _search;
string line;
ifstream read;
int i =0;
while(i++<2)
{
cout<<"Enter the word to search"<<endl;
cin>>_search;
read.open("type.txt");
size_t pos,i=0;
if(read.is_open())
{
while (read.good())
{
i++;
getline(read,line);
pos = line.find(_search);
if(pos != string::npos)
{
cout<<i<<": "<<line<<endl;
}
else
{
cout<<"Not found"<<endl;
}
}
read.close();
}
}
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string search,line;
ifstream read;
int i =0;
while(i<2)
{
read.open("type.txt");
cout<<"Enter the word to search"<<endl;
cin>>search;
size_t pos;
if(read.is_open())
{
while (getline(read,line))
{
pos = line.find(search);
if(pos != string::npos)
{
cout<<line<<endl;
read.close();
}
}
}
i++;
}
system("pause");
}