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;
}
有人可以告诉我为什么这个程序不会读取并显示来控制文件???我的意思是写得很完美。我尝试改变东西,但没有任何效果我在线检查了类似的代码,但仍然没有。
答案 0 :(得分:0)
有一些问题:
同意docs指定ios::ate
在打开后立即寻找流的结尾
所以没有什么可读的,你的while
循环永远不会被输入。
另一个问题是:operator >> (istream& stream, WebSites data)
您的运营商正在使用数据填写副本。要解决这个第二个参数应该是一个参考:
operator >> (istream& stream, WebSites& data)