以后尽量不用cin、cout啦

本文探讨了C++中cin与cout相较于scanf在处理double类型数据时存在的问题,包括输出不一致及读取机制相对繁琐导致的效率低下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cout输出有问题(对于double,不同OJ处理的结果不一样),cin读入机制较scanf繁琐。慢!!!!!!!!

转载于:https://www.cnblogs.com/chaiwentao/p/3947824.html

#include <iostream> #include <vector> #include <string> #include <fstream> #include <ctime> #include <queue> #include <algorithm> #include <map> #include <iomanip> using namespace std; class FlightSystem; class Serializable { public: virtual void serialize(ofstream& out) const = 0; virtual void deserialize(ifstream& in) = 0; virtual ~Serializable() {} }; // 虚基类 - 用户基类 class User: public Serializable { protected: string id; string name; string phone; public: User(const string& id, const string& name, const string& phone) : id(id), name(name), phone(phone) {} virtual ~User() {} virtual void showMenu() = 0; // 纯虚函数 void serialize(ofstream& out) const override { out << id << "," << name << "," << phone; } void deserialize(ifstream& in) override { getline(in, id, ','); getline(in, name, ','); getline(in, phone); } }; class FlightBase:public Serializable { public: virtual double calculateCurrentPrice() const = 0; virtual void display() const = 0; virtual ~FlightBase() {} }; class Date { public: int year; int month; int day; Date() : year(0), month(0), day(0) {} Date(int y, int m, int d) : year(y), month(m), day(d) {} friend ostream& operator<<(ostream& os, const Date& date) { os << setfill('0') << setw(4) << date.year << "-" << setfill('0') << setw(2) << date.month << "-" << setfill('0') << setw(2) << date.day; return os; } }; // 航班信息类 class Flight:public FlightBase { protected: string flightNumber; string airline; string departure; string destination; string planeModel; Date flightDate; int maxPassengers; int remainingTickets; double originalPrice; double currentPrice; // 计算动态票价 // 计算两个日期之间的天数差(仅处理6月和7月) int calculateDaysLeft(const Date& current) const { // 假设年份相同,且月份仅为6或7 if (current.month == 6 && flightDate.month == 6) { return flightDate.day - current.day; // 6月内 } else if (current.month == 6 && flightDate.month == 7) { return (30 - current.day) + flightDate.day; // 6月到7月 } else if (current.month == 7 && flightDate.month == 7) { return flightDate.day - current.day; // 7月内 } else { return -1; // 非法日期组合(如7月到6月) } } void calculateDynamicPrice(const Date& currentDate) { // 计算距离起飞的剩余天数(仅考虑6月和7月) int daysLeft = calculateDaysLeft(currentDate); // 根据剩余天数调整票价 if (daysLeft > 20) { currentPrice = originalPrice * 0.8; // 提前20天以上8折 } else if (daysLeft > 10) { currentPrice = originalPrice * 0.9; // 提前10-20天9折 } else if (daysLeft >= 0) { currentPrice = originalPrice; // 10天内原价 } else { currentPrice = 0; // 航班已起飞 } } public: Flight(string number, string air, string dep, string des, string model, Date date, int maxp, double price) : flightNumber(number), airline(air), departure(dep), destination(des), planeModel(model), flightDate(date), maxPassengers(maxp), originalPrice(price) { time_t now = time(0); tm* ltm = localtime(&now); Date current(1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday); calculateDynamicPrice(current); // remainingTickets = maxPassengers; } // 运算符重载 /*friend istream& operator>>(istream& is, Flight& flight) { is >> flight.flightNumber >> flight.airline >> flight.departure >> flight.destination >> flight.planeModel >> flight.date >> flight.maxPassengers >> flight.remainingTickets >> flight.originalPrice; flight.calculateDynamicPrice(); return is; } friend ostream& operator<<(ostream& os, const Flight& flight) { os << flight.flightNumber << " " << flight.airline << " " << flight.departure << " " << flight.destination << " " << flight.planeModel << " " << flight.date << " " << flight.maxPassengers << " " << flight.remainingTickets << " " << flight.originalPrice << " " << flight.currentPrice; return os; }*/ // friend ifstream& operator>>(ifstream& in, Flight& flight); // friend ofstream& operator<<(ofstream& out, const Flight& flight); // 订票功能 bool bookTickets(int count) { if (count <= remainingTickets) { remainingTickets -= count; // 获取当前日期重新计算价格 time_t now = time(0); tm* ltm = localtime(&now); Date current(1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday); calculateDynamicPrice(current); return true; } return false; } // 退票功能 void refundTickets(int count) { remainingTickets += count; if (remainingTickets > maxPassengers) remainingTickets = maxPassengers; // 获取当前日期重新计算价格 time_t now = time(0); tm* ltm = localtime(&now); Date current(1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday); calculateDynamicPrice(current); } // 序列化实现 void serialize(ofstream& out) const override { out << flightNumber << "," << airline << "," << departure << "," << destination << "," << planeModel << "," << flightDate << "," << maxPassengers << "," << remainingTickets << "," << originalPrice << "," << currentPrice; } void deserialize(ifstream& in) override { getline(in, flightNumber, ','); getline(in, airline, ','); getline(in, departure, ','); getline(in, destination, ','); getline(in, planeModel, ','); in >> flightDate.year; in.ignore(); in >> flightDate.month; in.ignore(); in >> flightDate.day; in.ignore(); in >> maxPassengers; in.ignore(); in >> remainingTickets; in.ignore(); in >> originalPrice; in.ignore(); in >> currentPrice; in.ignore(); } // 显示航班信息 void display() const override { cout << flightNumber << "\t" << airline << "\t" << departure << "\t" << destination << "\t" << planeModel << "\t" << flightDate << "\t" << originalPrice << "\t" << currentPrice << "\t" << remainingTickets << endl; } double calculateCurrentPrice() const override { return currentPrice; } // Getter方法 string getFlightNumber() const { return flightNumber; } string getAirline() const { return airline; } int getRemainingTickets() const { return remainingTickets; } float getCurrentPrice() const { return currentPrice; } // 其他成员函数... }; /*ifstream& operator>>(ifstream& in, Flight& flight) { flight.deserialize(in); return in; } ofstream& operator<<(ofstream& out, const Flight& flight) { flight.serialize(out); return out; }*/ // 客户类 class Customer : public User { private: vector< pair<string, int> > bookedFlights; public: Customer(const string& id, const string& name, const string& phone) : User(id, name, phone) {} friend istream& operator>>(istream& input, Customer& c) { cout << "输入身份证号: "; input >> c.id; cout << "输入姓名: "; input >> c.name; cout << "输入电话: "; input >> c.phone; return input; } // 重载输出运算符 friend ostream& operator<<(ostream& output, Customer& c) { output << "身份证: " << c.id << ' ' << " 姓名: " << c.name << ' ' << " 电话: " << c.phone; return output; } void showMenu() override { int choice; do { cout << "\n===== 客户菜单 =====" << endl; cout << "1. 查询航班" << endl; cout << "2. 订票" << endl; cout << "3. 退票" << endl; cout << "4. 退出" << endl; cout << "请选择: "; cin >> choice; switch (choice) { case 1: { FlightSystem system; for (auto& flight : system.getAllFlights()) { flight.display(); } break; } case 2: // 需要FlightSystem实例 break; case 3: // 需要FlightSystem实例 break; case 4: return; default: cout << "无效选择!" << endl; } } while (choice != 4); } void bookTicket(FlightSystem& system);//订票功能 void cancelTicket(FlightSystem& system);//退票功能 void serialize(ofstream& out) const override { User::serialize(out); out << "," << bookedFlights.size();//用于获取乘客已预定的航班数量 for (std::vector<std::pair<std::string, int>>::const_iterator it = bookedFlights.begin(); it != bookedFlights.end(); ++it) { out << "," << it->first << "," << it->second; } void deserialize(ifstream& in) override { User::deserialize(in); int size; in >> size; in.ignore(); bookedFlights.clear(); for (int i = 0; i < size; i++) { string flightNumber; int count; getline(in, flightNumber, ','); in >> count; in.ignore(); bookedFlights.push_back({flightNumber, count}); } } }; // 管理员类 class Admin : public User { public: Admin(const string& id = "", const string& name = "", const string& phone = "") : User(id, name, phone) {} void showMenu() override { int choice; do { cout << "\n===== 管理员菜单 =====" << endl; cout << "1. 添加航班" << endl; cout << "2. 编辑航班" << endl; cout << "3. 删除航班" << endl; cout << "4. 查看乘客" << endl; cout << "5. 退出" << endl; cout << "请选择: "; cin >> choice; FlightSystem system; switch (choice) { case 1: addFlight(system); break; case 2: editFlight(system); break; case 3: deleteFlight(system); break; case 4: viewPassengers(system); break; case 5: return; default: cout << "无效选择!" << endl; } } while (choice != 5); } void addFlight(FlightSystem& system);//增加航班 void editFlight(FlightSystem& system);// 编辑航班 void deleteFlight(FlightSystem& system);//删除航班 void viewPassengers(FlightSystem& system);// 查看乘客 }; class WaitingQueue { private: string flightNumber; queue< pair<string, int> > waitingQueue; // 乘客ID, 订票数量 public: WaitingQueue(const string& flightNum) : flightNumber(flightNum) {} void addToQueue(const string& passengerId, int count) { waitingQueue.push({passengerId, count}); } void processRefund(Flight& flight, int refundCount) { while (refundCount > 0 && !waitingQueue.empty()) { auto nextPassenger = waitingQueue.front(); if (refundCount >= nextPassenger.second) { if (flight.bookTickets(nextPassenger.second)) { refundCount -= nextPassenger.second; waitingQueue.pop(); } } else { break; } } } }; // 系统管理类 class FlightSystem { private: vector<Flight> flights; vector<Customer> customers; vector<Admin> admins; map<string, WaitingQueue> waitingQueues; // <航班号, 候补队列> // 文件路径 const string FLIGHT_FILE = "flights.txt"; const string CUSTOMER_FILE = "customers.txt"; const string ADMIN_FILE = "admins.txt"; public: FlightSystem() { loadData(); } ~FlightSystem() { saveData(); } // 数据加载与保存 void loadData() { // 加载航班 ifstream flightFile(FLIGHT_FILE); if (flightFile) { Flight flight; while (flightFile) { flight.deserialize(flightFile); if (!flightFile.fail() && !flight.getFlightNumber().empty()) { flights.push_back(flight); } } } // 加载客户 ifstream customerFile(CUSTOMER_FILE); if (customerFile) { Customer customer; while (customerFile) { customer.deserialize(customerFile); if (!customerFile.fail() && !customer.id.empty()) { customers.push_back(customer); } } } // 加载管理员 ifstream adminFile(ADMIN_FILE); if (adminFile) { Admin admin; while (adminFile) { admin.deserialize(adminFile); if (!adminFile.fail() && !admin.id.empty()) { admins.push_back(admin); } } } } void saveData() { // 保存航班 ofstream flightFile(FLIGHT_FILE); for (const auto& flight : flights) { flight.serialize(flightFile); flightFile << endl; } // 保存客户 ofstream customerFile(CUSTOMER_FILE); for (const auto& customer : customers) { customer.serialize(customerFile); customerFile << endl; } // 保存管理员 ofstream adminFile(ADMIN_FILE); for (const auto& admin : admins) { admin.serialize(adminFile); adminFile << endl; } } // 航班操作 Flight* findFlight(const string& number) { for (auto& flight : flights) { if (flight.getFlightNumber() == number) { return &flight; } } return nullptr; } void addFlight(const Flight& flight) { flights.push_back(flight); } void deleteFlight(const string& number) { flights.erase(remove_if(flights.begin(), flights.end(), [&](const Flight& f) { return f.getFlightNumber() == number; }), flights.end()); } // 排序航班 void sortFlights(const string& criteria) { if (criteria == "number") { sort(flights.begin(), flights.end(), [](const Flight& a, const Flight& b) { return a.getFlightNumber() < b.getFlightNumber(); }); } else if (criteria == "date") { sort(flights.begin(), flights.end(), [](const Flight& a, const Flight& b) { return a.date < b.date; }); } else if (criteria == "price") { sort(flights.begin(), flights.end(), [](const Flight& a, const Flight& b) { return a.getCurrentPrice() < b.getCurrentPrice(); }); } } // 用户登录 User* login() { string id, name, phone; cout << "请输入ID: "; cin >> id; cout << "请输入姓名: "; cin >> name; cout << "请输入电话: "; cin >> phone; // 查找客户 for (auto& c : customers) { if (c.id == id && c.name == name && c.phone == phone) { return &c; } } // 查找管理员 for (auto& a : admins) { if (a.id == id && a.name == name && a.phone == phone) { return &a; } } return nullptr; } // 处理候补队列 void processWaitingList(Flight& flight, int refundCount) { auto it = waitingQueues.find(flight.getFlightNumber()); if (it != waitingQueues.end()) { it->second.processRefund(flight, refundCount); } } // 主运行循环 void run() { while (true) { User* user = login(); if (user) { user->showMenu(); } else { cout << "登录失败,请重试!" << endl; } } } // 获取所有航班 vector<Flight>& getAllFlights() { return flights; } // 添加乘客 void addCustomer(const Customer& c) { Customer.push_back(c); } // 获取候补队列 WaitingQueue* getWaitingQueue(const string& flightNumber) { if (waitingQueues.find(flightNumber) == waitingQueues.end()) { waitingQueues[flightNumber] = WaitingQueue(flightNumber); } return &waitingQueues[flightNumber]; } vector<Customer>& getCustomers() { return customers; } }; // 客户类实现 void bookTicket(FlightSystem& system) { string flightNumber; int count; cout << "请输入航班号: "; cin >> flightNumber; cout << "请输入订票数量: "; cin >> count; Flight* flight = system.findFlight(flightNumber); if (!flight) { cout << "航班不存在!" << endl; return; } if (flight->bookTickets(count)) { bookedFlights.push_back({flightNumber, count}); cout << "订票成功!总价: " << flight->getCurrentPrice() * count << "元" << endl; } else { cout << "余票不足!当前余票: " << flight->getRemainingTickets() << endl; cout << "1. 重新选择航班" << endl; cout << "2. 排队候补" << endl; int option; cin >> option; if (option == 2) { WaitingQueue* queue = system.getWaitingQueue(flightNumber); queue->addToQueue(id, count); cout << "已加入候补队列!" << endl; } } } void cancelTicket(FlightSystem& system) { string flightNumber; cout << "请输入要退票的航班号: "; cin >> flightNumber; auto it = find_if(bookedFlights.begin(), bookedFlights.end(), [&](const pair<string, int>& p) { return p.first == flightNumber; }); if (it == bookedFlights.end()) { cout << "未找到该航班的订票记录!" << endl; return; } int count = it->second; Flight* flight = system.findFlight(flightNumber); if (flight) { flight->refundTickets(count); bookedFlights.erase(it); cout << "退票成功!退款金额: " << flight->getCurrentPrice() * count << "元" << endl; system.processWaitingList(*flight, count); } } // 管理员类实现 void addFlight(FlightSystem& system) { string number, airline, dep, des, model; int year, month, day, maxPass; double price; cout << "输入航班号: "; cin >> number; cout << "输入航空公司: "; cin >> airline; cout << "输入出发地: "; cin >> dep; cout << "输入目的地: "; cin >> des; cout << "输入飞机型号: "; cin >> model; cout << "输入日期 (年 月 日): "; cin >> year >> month >> day; cout << "输入最大乘客数: "; cin >> maxPass; cout << "输入原始价格: "; cin >> price; Date date(year, month, day); Flight flight(number, airline, dep, des, model, date, maxPass, price); system.addFlight(flight); cout << "航班添加成功!" << endl; } void editFlight(FlightSystem& system) { string number; cout << "输入要编辑的航班号: "; cin >> number; Flight* flight = system.findFlight(number); if (!flight) { cout << "航班不存在!" << endl; return; } // 简化的编辑功能 double newPrice; cout << "输入新价格: "; cin >> newPrice; // 实际实现中需要修改航班对象 cout << "编辑功能尚未完全实现" << endl; } void deleteFlight(FlightSystem& system) { string number; cout << "输入要删除的航班号: "; cin >> number; system.deleteFlight(number); cout << "航班删除成功!" << endl; } void viewPassengers(FlightSystem& system) { string flightNumber; cout << "请输入航班号: "; cin >> flightNumber; cout << "\n===== 乘客信息 =====" << endl; for (const auto& c : system.getCustomers()) { for (const auto& booking : c.bookedFlights) { if (booking.first == flightNumber) { cout << "姓名: " << c.name << "\t身份证: " << c.id << "\t电话: " << c.phone << "\t票数: " << booking.second << endl; } } } } /*void login(AirTicketSystem& system) { while (true) { cout << "\n===== 航空订票系统 =====" << endl; cout << "1. 客户登录" << endl; cout << "2. 管理员登录" << endl; cout << "3. 退出系统" << endl; cout << "请选择: "; int choice; cin >> choice; if (choice == 3) { system.saveFlights(); cout << "系统数据已保存,再见!" << endl; } string id, name, phone; cout << "请输入身份证号: "; cin >> id; cout << "请输入姓名: "; cin >> name; cout << "请输入电话: "; cin >> phone; if (choice == 1) { Customer customer(id, name, phone); customer.showMenu(); int customerChoice; while (cin >> customerChoice) { switch (customerChoice) { case 1: // 查询航班 break; case 2: // 订票 customer.bookTicket(); break; case 3: // 退票 customer.cancelTicket(); break; case 4: // 退出 return; default: cout << "无效选择,请重试!" << endl; } customer.showMenu(); } } else if (choice == 2) { Admin admin(id, name, phone); admin.showMenu(); int adminChoice; while (cin >> adminChoice) { switch (adminChoice) { case 1: // 添加航班 admin.addFlight(); break; case 2: // 编辑航班 admin.editFlight(); break; case 3: // 删除航班 admin.deleteFlight(); break; case 4: // 查看乘客 admin.viewPassengers(); break; case 5: // 退出 return; default: cout << "无效选择,请重试!" << endl; } admin.showMenu(); } } } }*/ int main() { FlightSystem system; system.run(); return 0; } 找错并帮我修改
最新发布
06-24
`cin >> s + 1;` 这种表达式的意图可能是想将输入跳过第一个字符存储到字符串 `s` 中的第二个位置开始。但是,这种写法存在潜在的问题,并不是一种安全或推荐的做法。 ### 解释 1. **原始形式**: ```cpp cin >> s + 1; ``` - 假设`s`是一个字符数组(如`char s[SIZE]`),那么这里的`s + 1`实际上是指向数组第二个元素 (`s[1]`) 的指针。 - 如果`s`是`std::string`类型,则上述操作不符合标准语法,因为对`std::string`直接做加法运算无意义。 2. **正确的替代方案**: #### 方案一:对于C风格字符串 (char[]) 如果你想从第2个字符的位置开始读取数据到一个已经初始化好的足够大的字符数组中,可以这样做: ```cpp #include <iostream> using namespace std; int main() { char buffer[50]; // 确保buffer有足够的空间存放结果加上终止符'\0' cout << "Enter string after skipping first character input :"; getchar(); // 跳过前面的一个字符(例如空格、换行) cin.getline(buffer, sizeof(buffer)); return 0; } ``` 注意这种方法需要手动处理好边界情况并且确保不会溢出缓冲区。 #### 方案二:对于 C++ 标准库字符串 (std::string) 如果你正在使用的是`std::string`, 推荐的方式是在接收完整个串之后再对其进行切片操作而不是试图通过偏移量来控制输入流的行为. ```cpp #include <iostream> #include <string> int main(){ string fullString; cout << "请输入完整字符串:"; getline(cin,fullString); if (!fullString.empty()){ string subStr = fullString.substr(1); cout<<"去掉首字母后的:"<<subStr<<endl; }else{ cout <<"输入为空" ; } return 0; } ``` 这种方式更直观易懂也更符合现代C++的习惯用法。 #### 注意事项 - 使用 `cin >> ...` 形式读入时,默认会忽略前导空白字符(包括空格、制表符和新行)。因此如果目的是为了略过特定单个非空白字符,请考虑其他方法比如先读取然后丢弃该字符(`getchar()` 或者 `ignore()`) - 对于动态分配内存的情况务必小心越界访问的风险,在不确定长度的情况下尽量采用能自动管理大小的数据结构如`std::vector<char>`或者直接利用`std::string`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值