gpt4 book ai didi

C++ 文件 I/O 我无法读取 .dat 文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:56 30 4
gpt4 key购买 nike

using namespace std;

struct WebSites
{
string siteName;
int rank;

string getSiteName() { return siteName; }
int getRank() { return rank; }
WebSites(string const&, int);
WebSites();
};

WebSites::WebSites(string const& siteName, int rank) {
this->siteName = siteName;
this->rank = rank;

}

WebSites::WebSites() {}

ostream& operator << (ostream& stream, WebSites const& data) {
stream << data.rank << " " << data.siteName.size() << " " << data.siteName<< endl;
return stream;

}

istream& operator >> (istream& stream, WebSites data) {
stream >> data.siteName >> data.rank;
return stream;

}


int main() {

WebSites s1("www.google.co.uk", 1);

//write to file

ofstream writer("chou.dat", ios::out | ios::binary); //i'll add ios::app later
if (!writer) {
cout << " error opening file " << endl;
return -1;
}
else {
writer << s1.getSiteName() << " " << s1.getRank() << endl;
}
writer.close();

//read file
fstream writerR("chou.dat", ios::binary | ios::in | ios::ate);
WebSites read;
while (writerR >> read) {

cout << read.siteName << " rank: "<< read.rank << endl;
}
writerR.close();
return 0;
}

有人能告诉我为什么这个程序不能读取和显示控制台文件吗???我的意思是它写得很完美。我尝试更改内容,但没有任何效果我在网上检查了类似的代码,但仍然没有。

最佳答案

有一些问题:

  1. 根据 docs指定 ios::ate

    seek to the end of stream immediately after open

    所以根本没有什么可读的,你的 while 循环将永远不会进入。

  2. 另一个问题在这里:operator >> (istream& stream, WebSites data)

    您的运算符(operator)正在用数据填充拷贝。解决这个第二个参数应该是一个引用:

    operator >> (istream& stream, WebSites& data)

关于C++ 文件 I/O 我无法读取 .dat 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42373643/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com