-1
我從文件中讀入while循環不會中斷。我不確定問題是什麼。如果您需要更多信息,請詢問。文件循環和讀入地圖的問題
代碼:
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
class Customer {
public:
string name;
string address;
Customer() {}
};
class Purchase {
public:
string product_name;
double unit_price;
int count;
Purchase() {}
Purchase(string pn, double up, int c) :product_name(pn), unit_price(up), count(c) {}
};
// Function Object for comparison in map container
struct Cmp_name {
bool operator()(const Customer& first, const Customer& second)
{ return first.name < second.name; }
};
// ostream overloads
ostream& operator<<(ostream& out, const Customer& c)
{
out << c.name << '\n'
<< c.address << '\n';
return out;
}
ostream& operator<<(ostream& out, const Purchase& p)
{
out << p.product_name << '\n'
<< p.unit_price << '\n'
<< p.count << '\n';
return out;
}
istream& operator>>(istream& in, Customer& c)
{
getline(in, c.name);
getline(in, c.address);
return in;
}
istream& operator>>(istream& in, Purchase& p)
{
getline(in, p.product_name);
in >> p.unit_price >> p.count;
return in;
}
int main()
{
cout << "Enter file to read orders from: \n";
string file;
cin >> file;
ifstream is(file.c_str());
if (!is) cerr << "File doesn't exist.\n";
multimap<Customer, Purchase, Cmp_name> orders;
while (!is.eof()) {
Customer c;
Purchase p;
is >> c;
is >> p;
orders.insert(make_pair(c,p));
}
for (multimap<Customer, Purchase, Cmp_name>::iterator it = orders.begin(); it!=orders.end(); ++it)
cout << it->first << it->second << "\n\n";
}
我實際上通常把它當作const類型&var,但是謝謝 - 愚蠢的錯誤。我會嘗試你的測試,看看我想出了什麼。 – trikker 2009-09-01 01:51:28
爲了更簡潔的代碼,我重載了istream,但它仍然有一個無限循環。我用一些輸出做了一段時間(真正的)測試,它通過數據循環兩次然後凍結。 – trikker 2009-09-01 02:04:27
那是因爲你沒有「if(!(is >> c))break;」 – 2009-09-01 02:23:20