Home > other >  Loop and object intialization question (C )
Loop and object intialization question (C )

Time:09-17

I'm trying to use a loop to infinitely create objects from a class unless a specific input is entered. I think I have everything done except the loop. I know how to initialize one object in my main function, but I'm stuck as to how to use a loop to do this infinitely. My code is below.

Driver File:

    #include <iostream>

    #include "square.h"

    using namespace std;

int main()
{
    square square1;
    square1.setSide();
    square1.calcArea();
    square1.calcPerimeter();
    square1.showData();
}

Header file:

#pragma once

#include <string>

class square
{
public:
    square();

    void setSide();

    double getSide() const;

    void calcPerimeter();
    void calcArea();
    void showData();

private:
    double squareSide;
    double squarePerimeter;
    double squareArea;
};

Implementation file:

#include <iostream>
#include <iomanip>

#include "square.h"

square::square()
{
    squareSide = 0;
    squarePerimeter = 0;
    squareArea = 0;
}

void square::setSide()
{   
    std::cout << "Enter a side length: ";
    std::cin >> squareSide;
    std::cout << "\n";

    if (squareSide == -1)
    {
        std::cout << "Exiting program.\n";
        exit(-1);
    }

    while (std::cin.fail() || squareSide < 0)
    {
        std::cout << "\nYou must enter a positive number. Please try again.\n\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Enter a side length: ";
        std::cin >> squareSide;
    }
}

double square::getSide() const
{
    return squareSide;
}

void square::calcPerimeter()
{
    squarePerimeter = 4 * getSide();
}
void square::calcArea()
{
    squareArea = getSide() * getSide();
}
void square::showData()
{
    std::cout << "The side length of the square is: " << getSide() << "\n";
    std::cout << "The perimeter of the square is: " << getSide() * 4 << "\n";
    std::cout << "The area of the square is: " << getSide() * getSide() << "\n";
}

CodePudding user response:

You could add a do ... while loop around your code in main and store the squares in a vector<square>.

Example:

#include <limits>  // you use numeric_limits from this header
#include <utility> // move
#include <vector>  // vector

int main() {
    std::vector<square> squares;
    std::string answer;
    do {
        square square1;
        square1.setSide();
        square1.calcArea();
        square1.calcPerimeter();

        // move the square into the vector
        squares.push_back(std::move(square1));

        // ask the user if he/she wants to enter another
        std::cout << "Go again? ";
    } while(std::cin >> answer && answer == "yes");

    // display what you stored
    std::cout << "You stored " << squares.size() << " square(s)\n";
    for(square& sq : squares) {
        sq.showData();
        std::cout << '\n';
    }
}
  • Related