[英]Program using fstream will not complile
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
class InsurancePolicy
{
friend fstream& operator<<(fstream&, InsurancePolicy);
friend istream& operator>>(istream&, InsurancePolicy&);
private:
int policyNum;
string lastName;
int value;
int premium;
};
fstream& operator<<(fstream& out, InsurancePolicy pol)
{
out << pol.policyNum << " " << pol.lastName << " " << pol.value << " " << pol.premium << endl;
return out;
}
istream& operator>>(istream& in, InsurancePolicy& pol)
{
in >> pol.policyNum >> pol.lastName >> pol.value >> pol.premium;
return in;
}
int main()
{
ofstream outfile;
outFile.open("Policy.txt");
Policy aPolicy[10];
for (int count = 0; count < 10; ++count)
{
printf("Enter the policy number, the holder's last name, the value, and the premium.");
cin >> aPolicy[count];
outfile << aPolicy[count] << endl;
}
}此程序應從鍵盤接受值並將它們打印到文件中。 但是,它給出了許多語法錯誤。
嚴重性代碼說明項目文件行抑制狀態錯誤C2065'outFile':未聲明的標識符Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 39
錯誤'.open'左邊的錯誤C2228必須具有class / struct / union Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 39
錯誤C2065“政策”:未聲明的標識符Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 40
錯誤C2146語法錯誤:缺少';' 標識符'aPolicy'Project6之前c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 40
錯誤C2065'aPolicy':未聲明的標識符Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 40
錯誤C2065'aPolicy':未聲明的標識符Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 44
錯誤C2065'aPolicy':未聲明的標識符Project6 c:\\ users \\ preston freeman \\ source \\ repos \\ jave.cpp 45
如何解決這些錯誤? 感謝您的時間?
代碼中有很多錯別字,但是主要的問題是從fstream到ofstream沒有已知的轉換,因此這是代碼的正確版本:
#include <iostream>
#include <fstream>
using namespace std;
class InsurancePolicy
{
friend ofstream& operator<<(ofstream&, InsurancePolicy);
friend istream& operator>>(istream&, InsurancePolicy&);
private:
int policyNum;
string lastName;
int value;
int premium;
};
ofstream& operator<<(ofstream& out, InsurancePolicy pol)
{
out << pol.policyNum << " " << pol.lastName << " " << pol.value << " " << pol.premium << endl;
return out;
}
istream& operator>>(istream& in, InsurancePolicy& pol)
{
in >> pol.policyNum >> pol.lastName >> pol.value >> pol.premium;
return in;
}
int main() {
ofstream outFile;
outFile.open("Policy.txt");
InsurancePolicy aPolicy[10];
for (int count = 0; count < 10; ++count)
{
printf("Enter the policy number, the holder's last name, the value, and the premium.");
cin >> aPolicy[count];
outFile << aPolicy[count]<<std::endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.