C++编写House类程序运行时输出窗口崩溃,求问题排查与修复方案
错误排查
- 野指针访问崩溃:main函数中定义的
House* h[100]是未初始化的指针数组,没有分配实际的House对象内存,直接调用->getData()属于非法内存访问,是程序崩溃的直接原因;同时不符合题目要求的「声明包含100个House类对象的数组available」的要求。 - 输入缓冲区异常:
getline和cin混用时,输入流会残留换行符,会导致下一次getline直接读取到空内容,出现输入跳过的问题。 - 基础依赖缺失:原代码未引入
<iostream>、<string>必要头文件,也未声明标准命名空间,无法直接编译运行。 - 未做长度校验:题目要求业主、地址最长为20字符,原代码没有对应的截断校验逻辑。
- 输出逻辑不符合要求:题目要求所有输入完成后统一输出所有已录入条目,原代码仅单条录入后临时输出。
修复后可运行代码
#include <iostream> #include <string> using namespace std; class House { private: string owner; string address; int bedrooms; float price; // 字符串截断工具函数,限制最大长度 string limitStrLength(string str, int maxLen) { if (str.length() > maxLen) { return str.substr(0, maxLen); } return str; } public: House(string owner = "", string address = "", int bedrooms = 0, float price = 0.0) { this->owner = limitStrLength(owner, 20); this->address = limitStrLength(address, 20); this->bedrooms = bedrooms; this->price = price; } void setOwner(string owner) { this->owner = limitStrLength(owner, 20); } void setAddress(string address) { this->address = limitStrLength(address, 20); } void setBedrooms(int bedrooms) { this->bedrooms = bedrooms; } void setPrice(float price) { this->price = price; } string getOwner() { return owner; } string getAddress() { return address; } int getBedrooms() { return bedrooms; } float getPrice() { return price; } void getData() { cout << "Enter Owner : "; string temp; // 忽略前序残留的换行符 cin.ignore(); getline(cin, temp); setOwner(temp); cout << "Enter Address : "; getline(cin, temp); setAddress(temp); cout << "Number of Bedrooms? : "; cin >> bedrooms; setBedrooms(bedrooms); cout << "Price : "; cin >> price; setPrice(price); cout << endl; } void display() { cout << owner << "\t" << address << "\t" << bedrooms << "\t" << price << endl; } }; int main() { // 符合题目要求的100个House对象的数组available House available[100]; int count = 0; char yesorno; do { available[count].getData(); count++; // 最多录入100条 if (count >= 100) { cout << "已达到最大录入上限100条" << endl; break; } cout << "Do you wish to continue ?"; cin >> yesorno; } while ((yesorno == 'y' || yesorno == 'Y') && count < 100); // 输入完成后统一输出所有已录入内容 cout << endl << "===== 已录入的所有房屋信息 =====" << endl; cout << "Owner \t Address \t Bedrooms \t Price" << endl; for (int i = 0; i < count; i++) { available[i].display(); } return 0; }
内容的提问来源于stack exchange,提问作者codeplayer
相关产品推荐
相关产品推荐

