【问题标题】:ifstream not pulling any data inifstream 没有拉入任何数据
【发布时间】: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;
}

【问题讨论】:

  • 你的构造函数不应该是公开的吗?`

标签: c++ fstream ifstream


【解决方案1】:

问题是:

1) 当find 开始时,你的文件在最后,因为你打开它之后,为了读取tellg 的大小,你一直寻找到最后,但是你把它保留在最后。那么:

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
        }

如果在第一次测试中应用了else,它会起作用,但实际上,如果你将lastN 初始化为“Rathbone”并将currLast 初始化为"!!",则它会成功。因此,您尝试从文件末尾进一步查找文件,因此它会卡在末尾,您将无法读取任何内容。

解决方案:在构造函数的末尾,将文件查找到其开头:

cs.seekg(0, ios_base::beg); 

【讨论】:

  • 谢谢!感谢您的意见;它的轮廓非常好。
【解决方案2】:

删除cs.seekg(0,ios::end);

您正在将文件指针设置为文件末尾。因此,没有什么可进一步阅读的。

此外,最好在每次使用时检查流提取是否正常工作。这就是你的做法..

if ( ! ( cs >> lastN >> firstN >> cardNum ) );
    CallErrorHandlingCode(); // Throw exception, or print to console, or exit program.

如果您像上面那样编写流提取,您就会在运行时发现错误。

【讨论】:

  • 先谢谢詹斯!我意识到我的问题。你是对的!我已经走到了尽头,应该注意到这一点。我正在打电话以了解该文件最初有多长时间以供将来参考。之后我应该回到文件的开头。我也应该设置 currLength = cs.tellg();在我退出 if 之后。谢谢!
  • @BitShift 乐于助人:)
猜你喜欢
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 2013-05-09
  • 2021-12-23
  • 2022-01-21
相关资源
最近更新 更多