又是文件中字符串显示问题(比较棘手)
e:\test1文件内容如下:
Begin:
this is the 100th line;
not the 99th line;
this is the 100th line;
end;
Begin:
this is the 101th line;
not the 100th line;
this is the 101th line;
end;
Begin:
this is the 102th line;
not the 101th line;
this is the 102th line;
end;
要求从键盘录入一个字符如“101”,显示
Begin:
this is the 101th line;
not the 100th line;
this is the 101th line;
end;
而不能显示
Begin:
this is the 102th line;
not the 101th line;
this is the 102th line;
end;
求完整程序,万分感谢,100分全奖励第一个给出能运行的答案的人!
[解决办法]
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
//#include <sys\stat.h>
//#include <string.h>
//#include <time.h>
//#include <stdio.h>
//#include <stdlib.h>
int main(int argc, char *argv[])
{
int num;
cout < < "Input num: ";
cin> > num;
char tmp[40];
sprintf(tmp, "this is the %dth line; ", num); //构造比较串
ifstream infile( "test.txt ");
string line;
while(!infile.eof())
{
getline(infile, line);
if(line == "Begin: ") //开始串匹配
{
getline(infile, line);
if(line==tmp) //匹配比较串
{
cout < < "Begin: " < <endl;
cout < <line < <endl;
while(line != "end; ") //循环读取输出,直到 end; 结束
{
getline(infile, line);
cout < <line < <endl;
}
break;
}
}
}
system( "pause ");
return 0;
}
test.txt文件内容(当前目录下):
Begin:
this is the 100th line;
not the 99th line;
this is the 100th line;
end;
Begin:
this is the 101th line;
not the 100th line;
this is the 101th line;
end;
Begin:
this is the 102th line;
not the 101th line;
this is the 102th line;
end;
[解决办法]
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void ReadBlock(ifstream& infile,
string const& begin,
string const& end,
string& block)
{
string line;
bool foundBegin = false;
bool foundEnd = false;
while (infile && !infile.eof()) {
getline(infile, line);
string::size_type idxSub = string::npos;
if ( !foundBegin) idxSub = line.find(begin, 0);
if ( idxSub!=string::npos) {
foundBegin = true;
}
if ( foundBegin) {
block.append(line);
block.append( "\n ");
idxSub = line.find(end, 0);
if (idxSub != string::npos) {
foundEnd = true;
}
}
if (foundEnd) break;
}
if ( !foundBegin || !foundEnd )
{
block.clear();
}
}
void PrintBlockInFile(string const& filename,
string const& begin,
string const& end,
string const& what
)
{
ifstream inf(filename.c_str());
if (!inf) {
cout < < "Error: can 't open the file: " < <filename < <endl;
exit(1);
}
string block;
int nSubStrFound = 0;
while (inf && !inf.eof()){
block.clear();
ReadBlock(inf, begin, end, block);
string::size_type idxNewLine = block.find( '\n ',0);
idxNewLine = block.find( '\n ',idxNewLine+1);
string::size_type idxSub = block.find(what, 0);
if ( idxSub != string::npos && idxSub < idxNewLine) {
cout < < block < <endl;
}
}
}
int main()
{
string filename;
cout < < "Please input the filename to seach:\t ";
cin> > filename;
string numStr;
cout < < "Please input the string to seach: \t ";
cin> > numStr;
string beginStr = "Begin ";
string endStr = "end ";
PrintBlockInFile(filename, beginStr, endStr, numStr);
system( "pause ");
return 0;
}