【发布时间】:2015-11-23 10:29:51
【问题描述】:
我正在编写下面的代码,该代码对已排序的文本文件执行二进制印章搜索。文本文件如下所示:
Amerse Gregorina 5465874526370945
安德森鲍勃 4235838387422002
Legstrong-Cones Mike 8238742438632892
目前,我的构造函数(用于调试)中的 getline 正确提取了第一行数据。但是,当我调用我的 findmethod 时,getline 和带有变量的 cs
#include <iostream>
#include <fstream>
using namespace std;
class CardSearch {
protected:
ifstream cs;
public:
int currLength;
CardSearch(string fileName) {
/* Make sure our file stream opens properly
pos = current position -> set at 0 to begin
I use seekg to go to the end of the file and tellg me how many bytes we read to go to the end */
cs.open(fileName, ios::in);
if(cs.fail()) {
cerr << "Failed to open file\n";
exit(1);
}
string dummy;
getline(cs,dummy); // debug print
cout << dummy << endl;
cs.seekg(0,ios::end);
currLength= (int)cs.tellg();
}
string find( string lastN, string firstN) {
string cardNum;
string currLast = "!!";
string currFirst = "!!";
string dummy;
while (currLast != lastN && currFirst != firstN) {
currLength = currLength/2;
if (lastN > currLast) {
cs.seekg(currLength, ios::cur); // if the lastName given is > where we are, move forward
} else {
cs.seekg((-1 * currLength), ios::cur); // // if the lastName given is < where we are, move backward
}
cs >> lastN >> firstN >> cardNum;
cout << currLast << " " << currFirst << " : " << cardNum << endl;
}
return cardNum;
}
};
int main(int argc, const char * argv[]) {
CardSearch instance("StolenNumbers.txt");
string s = instance.find("Rathbone", "Luke");
return 0;
}
【问题讨论】:
-
你的构造函数不应该是公开的吗?`