我正在处理下面的代码,该代码对已排序的文本文件执行二进制搜索。文本文件如下所示:
Amerse Gregorina 5465874526370945
Anderson Bob 4235838387422002
Legstrong-Cones Mike 8238742438632892
目前我的构造函数中的getline(用于调试)正确地引入了第一行数据。但是,当我调用我的findmethod时,getline和cs<<用变量拉入NO DATA。我尝试使用指针,getLine也没有任何内容。我已经通过StackOverflow进行了整理,并做了一些谷歌搜索来帮助解决这个问题,但似乎无法解决问题。任何帮助/解释将不胜感激。如果您有任何疑问,请告诉我。谢谢!
#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;
}
答案 0 :(得分:0)
删除cs.seekg(0,ios::end);
您正在将文件指针设置为文件末尾。因此,没有什么可读的了。
另外,每次使用时检查流提取是否正常工作是个好主意。你就是这样做的。
if ( ! ( cs >> lastN >> firstN >> cardNum ) );
CallErrorHandlingCode(); // Throw exception, or print to console, or exit program.
如果您像上面那样编写流提取,那么您将在运行时捕获该错误。
答案 1 :(得分:0)
问题在于:
1)当protected void Cookie_Encode(object sender, EventArgs e)
{
// Encoding username in Base64
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(User_box.Text);
string Encoded_user = System.Convert.ToBase64String(plainTextBytes);
// Creating and setting the cookie
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UserName"] = Encoded_user;
myCookie.Expires = DateTime.Now.AddDays(7d);
Response.Cookies.Add(myCookie);
Response.Redirect(Request.RawUrl);
}
启动时,您的文件就在最后,因为在您打开它之后,您会将其搜索到最后以便使用find
读取大小,但是您需要将其设置为结束。然后:
2)
tellg
如果在第一次测试中应用了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
}
,它会起作用,但实际上,如果成功,则因为您将else
初始化为&#34; Rathbone&#34;和currLast到lastN
。因此,你试图从它的结尾进一步寻找文件,所以它最终被卡住了,你不会读任何东西。
解决方案:在构造函数的末尾,找到文件的开头:
"!!"