怎么重复这堂课?

时间:2014-03-14 11:49:50

标签: c++ class object repeat

  1. 我想要求用户输入最多20个房屋的详细信息。我需要按用户输入的房屋数量重复我的问题。
  2. 然后我想在列表中显示详细信息
  3. #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    class House
    {
          private :
                 int NumRooms;
                 int Area;
                 int FloorNumber;
          public :
    
                 void Getdata()
                 {
                       cout << "Enter number of rooms in house: ";
                       cin >> NumRooms;
                       cout << "Enter area of house: ";
                       cin >> Area;
                       cout << "Enter floor number of house: ";
                       cin >> FloorNumber;
                 }
                 void Putdata()
                 {
                       cout  << "Number of rooms: " << NumRooms << endl;
                       cout << "Area of house: " << Area << endl;
                       cout << "Floor number: " << FloorNumber << endl;
                }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        House s;
        s.Getdata();
        s.Putdata();
        system("pause");
        return 0;
    }
    

2 个答案:

答案 0 :(得分:1)

#include <vector>

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Enter number of house you want to enter: ";
    int nhouses;
    cin >> nhouses;

    std::vector<House> houses;

    for (int i=0; i<nhouses; i++) {
        House s;
        s.Getdata();
        houses.push_back(s);
    }

    for (auto& hit = houses.begin(); hit != houses.end(); ++hit)
        hit->PutData();

    system("pause");
    return 0;
}

这实际上支持任意数量的房屋(超过20个)。如果你真的想将数字限制为20只需插入一个

if (nhouses > 20) {
    std::cout << "more than 20? you are a horrible person" << std::endl;
    return -1;
}

答案 1 :(得分:0)

我是c ++的新手,但是通过查看你的问题看起来有点模糊,但无论如何我都会去看看

1)如何将房子声明为数组          房子[30];

    and taking the inputs inside a for loop??? or a do-while