【发布时间】:2020-05-03 02:33:47
【问题描述】:
我为总线系统编写了此代码,但无法显示保存在 stud1 中的对象。我尝试使用 readData 但没有用。代码的目的是 1. 以总线信息的形式从用户接收输入并保存它们 2. 将所有总线输入输出到系统中(重新发布更改代码)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
string busType, busMake, regNum;
char menu();
int id = 0;
//int staff[50];
int carObjNum, option0;
int temp = 0;
char objArray[5];
string busMake0, busType0, regNum0;
class bus
{
public:
int i;
string busType;
string busMake;
string regNum;
char input();
char transHistory();
bus(string id = "", string name = "", string phone = "") : busMake(id), busType(name), regNum(phone)
{}
bool operator==(const bus & obj)
{
return (busMake == obj.busMake) && (busType == obj.busType) && (regNum == obj.regNum);
}
/*
* Write the member variables to stream objects
*/
friend ostream & operator << (ostream &out, const bus & obj)
{
out << obj.busMake << "\n" <<obj.busType<<"\n"<<obj.regNum<<endl;
return out;
}
/*
* Read data from stream object and fill it in member variables
*/
friend istream & operator >> (istream &in, bus &obj)
{
in >> obj.busMake;
in >> obj.busType;
in >> obj.regNum;
return in;
}
};
char bus::input(){
cout<<"Enter bus make\n"<<endl;
cin>>busMake0;
cout<<"Enter bus Type\n"<<endl;
cin>>busType0;
cout<<"Enter registration number\n"<<endl;
cin>>regNum;
vector<bus> vec = {};
bus stud1(busMake,busType, regNum);
vec.push_back(stud1);
ofstream out("bus.txt");
out<<stud1;
out.close();
// Open the File
ifstream in("bus.txt");
bus bus1;
in>>bus1;
in.close();
for(bus n : vec) {
std::cout << n << '\n';
}
return 0;
}
char bus::transHistory(){
bus stud1;
//Open the file that you just saved.
ifstream out("bus.txt");
//need this function to be able to read what was saved in stud1 at bus::input()
//then after that have all info output to user upon request.
out.close();
return 0;
}
int x;
char menu(){
int option;
cout<<"Welcome to the GTUC repair system\n"<<endl;
cout<<"What would you like to do?\n"<<endl;
cout<<""<<endl;
cout<<"Enter '1' to enter a new repair\n"<<endl;
cout<<"Enter '2' to print total transaction history\n"<<endl;
cin>>option;
option0 = option;
return option;
}
int main()
{
bus decision;
menu();
switch (option0) {
case 1:
decision.input();
menu();
case 2:
decision.transHistory();
default:
break;
}
return 0;
}
【问题讨论】:
-
什么是
readData?您确定在显示对象而不是保存对象时遇到问题吗? -
我想显示我保存在 bus.txt 中的所有对象,但无法执行此操作
-
你遇到了什么麻烦?请告诉我们“没用”的详细信息。
-
程序运行时,当
case 1被触发时,用户输入总线信息然后程序返回菜单。当case 2被触发后,它应该打印出所有已经输入但它是空白的总线信息 -
case 2的输出为空白,因为bus::transHistory()中没有打印语句。实现它。
标签: c++ class stdvector ofstream