2013-04-18 1 views
0

Так вот мой код:нужна помощь фиксируя незначительные проблемы в моей программе

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

class Point 
{ 
private: 
    double px; 
    double py; 

public: 
    void setX(const double x); 
    void setY(const double y); 
    double getX() const; 
    double getY() const; 
}; 

class Rectangle 
{ 
private: 
    string name; 
    Point blPoint; 
    double length, height; 

public: 
    // member functions 
    void setName(const string & inName); 
    void setBottomLeft(const double x, const double y); 
    void setDimensions(const double inLength, const double inHeight); 

    string getName() const; 
    Point getBottomLeft() const; 
    double getLength() const; 
    double getHeight() const; 

    double area() const; 
    double perimeter() const; 
    Point midPoint() const; 
    void scaleBy2(); 
    void display() const; 
}; 

// FUNCTION PROTOTYPES GO HERE: 
void welcome(); 
bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list); 
void read_coord(const string promptPoint, double & x, double & y); 
void read_length(const string promptLength, double & inLength, double & inHeight); 
void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list); 

int main() 
{ 
    // Define your local variables, e.g. a vector of class Rectangle 
    Rectangle rec; 
    vector<Rectangle> list; 
    string prompt1stName = "Enter the name of the first rectangle: "; 
    string promptName = "Enter the name of the next rectangle: "; 
    string errorInvalid = "Invalid input. Type 'rec' following by the name or 'stop' if done."; 
    string errorUsed = "This name is already being used!"; 
    string inName; 
    string Name; 

    // Display welcome banner 
welcome(); 

    /* Prompt user for first rectangle or 'stop' */ 
    bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 

    // WHILE user input is invalid 
    while (read == false) 
    { 

     // Display "Try again! " 
cout << "Try again! " << endl; 
     read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 
    } 

    // IF user input is not 'stop' 
     if (inName != "stop") 
    { 
     // Extract rectangle name from user input 
       int a = inName.length() - 4; 
     Name = inName.substr(4, a); 

     // Prompt for bottom left point 
       double x, y; 
     string promptPoint = "Enter " + Name + "'s bottom left x and y coords: "; 
     read_coord(promptPoint, x, y); 

     // Prompt for length and height 
       double inLength, inHeight; 
     string promptLength = "Enter " + Name + "'s length and height: "; 
     read_length(promptLength, inLength, inHeight); 

     // Add rectangle to the rectangle list 
     add_rec(Name, x, y, inLength, inHeight, list); 
    } 
    /* Prompt user for next rectangle or 'stop' */ 
    // WHILE user input not 'stop' 
     while (inName != "stop") 
    { 
     // Display "Thank you! " 
cout << "Thank you! "; 
bool read = read_rec(promptName, errorInvalid, errorUsed, inName, list); 

     // WHILE user input is invalid while (read == false) 
     { 

      // Display "Try again! " 
         cout << "Try again! " << endl; 
      read = read_rec(promptName, errorInvalid, errorUsed, inName, list); 
     } 

      // IF user input is not 'stop' 
        if (inName != "stop") 
     { 

       // Extract rectangle name from user input 
          int a = inName.length() - 4; 
      Name = inName.substr(4, a); 

       // Prompt for bottom left point 
          double x, y; 
      string promptPoint = "Enter " + Name + "'s bottom left x and y coords: "; 
      read_coord(promptPoint, x, y); 

       // Prompt for length and height 
          double inLength, inHeight; 
      string promptLength = "Enter " + Name + "'s length and height: "; 
      read_length(promptLength, inLength, inHeight); 


       // Add rectangle to the rectangle list 
      add_rec(Name, x, y, inLength, inHeight, list); 
     } 
    } 

    // IF the rectangle list is not empty 
     if (list.size() != 0) 
    { 
     // Display all rectangles in the rectangle list 
int rec_num = 0; 
int i = 1; 
while (i< list.size()) 
{ 
    rec_num++; 
    i++; 

} 
      cout << "You have " << rec_num+1 << " rectangle(s) in your list: "; 
      cout << endl; 

       for (int i = 0; i < list.size(); i++) 
     { 
      cout << "Rectangle '" << list[i].getName() << "' : "; 
      list[i].display(); 
      list[i].scaleBy2(); 
      cout << "  After scale by 2: "; 
      list[i].display(); 
      cout << endl; 
     } 
    } 

    // ELSE 
    else 
     { 
     // Display that no rectangles are in the list 
       cout << "You have no rectangles in your list." << endl; 
    } 

    return 0; 
} 

// FUNCTION DEFINITIONS GO HERE: 
void welcome() 
{ 
    cout << "Welcome! Create your own list of rectangles." << endl; 
    cout << "You will be asked to provide information about each rectangle in your list by name." << endl; 
    cout << "Type the word 'stop' for the rectangle name when you are done." << endl; 
    cout << endl; 
} 

bool read_rec(const string promptName, const string errorInvalid, const string errorUsed, string & inName, vector<Rectangle> & list) 
{ 
    cout << promptName; 
    getline(cin, inName); 

    if (inName == "stop") 
    { 
     return(true); 
    } 
    else if (inName.substr(0,4) != "rec ") 
    { 
     cout << errorInvalid; 
     return(false); 
    } 
    else 
    { 
     int j = 0; 
     for (int i = 0; i < list.size(); i++) 
     { 
      if (inName == "rec " + list[i].getName()) 
      { 
       j = j+1; 
      } 
     } 
     if (j == 0) 
     { 
      return(true); 
     } 
     if (j != 0) 
     { 
      cout << errorUsed; 
      return(false); 
     } 
    } 
} 

void read_coord(const string promptPoint, double & x, double & y) 
{ 
    cout << promptPoint; 
    cin >> x; 
    cin >> y; 
    } 

void read_length(const string promptLength, double & inLength, double & inHeight) 
{ 
    cout << promptLength; 
    cin >> inLength; 
    cin >> inHeight; 
    cout << endl; 

    while (inLength <= 0 || inHeight <= 0) 
    { 
     cout << "Make length and height positive values. Try again."; 
     cout << promptLength; 
     cin >> inLength; 
     cin >> inHeight; 
     cout << endl; 
    } 
} 

void add_rec(const string Name, double x, double y, double inLength, double inHeight, vector<Rectangle> & list) 
{ 
    Rectangle rec; 
    rec.setName(Name); 
    rec.setBottomLeft(x, y); 
    rec.setDimensions(inLength, inHeight); 
    list.push_back(rec); 
} 

// CLASS MEMBER FUNCTION DEFINITINOS GO HERE: 

void Point::setX(const double x) 
{ 
    px = x; 
} 

void Point::setY(const double y) 
{ 
    py = y; 
} 

double Point::getX() const 
{ 
    return (px); 
} 

double Point::getY() const 
{ 
    return (py); 
} 

void Rectangle::setName(const string & inName) 
{ 
    name = inName; 
} 

void Rectangle::setBottomLeft(const double x, const double y) 
{ 
    blPoint.setX(x); 
    blPoint.setY(y); 
} 

void Rectangle::setDimensions(const double inLength, const double inHeight) 
{ 
    length = inLength; 
    height = inHeight; 
} 

string Rectangle::getName() const 
{ 
    return (name); 
} 

Point Rectangle::getBottomLeft() const 
{ 
    return (blPoint); 
} 

double Rectangle::getLength() const 
{ 
    return (length); 
} 

double Rectangle::getHeight() const 
{ 
    return (height); 
} 

double Rectangle::area() const 
{ 
    // area = length * height 
    return(length * height); 
} 

double Rectangle::perimeter() const 
{ 
    // perimeter = 2 * (length + height); 
    return(2 * (length + height)); 
} 

Point Rectangle::midPoint() const 
{ 
    Point midPoint; 
    double mx = blPoint.getX() + 0.5 * length; 
    double my = blPoint.getY() + 0.5 * height; 
    midPoint.setX(mx); 
    midPoint.setY(my); 
    return(midPoint); 
} 

void Rectangle::scaleBy2() 
{ 
    double midx = blPoint.getX() + 0.5 * length; 
    double midy = blPoint.getY() + 0.5 * height; 
    double newblPx = midx - length; 
    double newblPy = midy - height; 
    length = 2*length; 
    height = 2*height; 
    blPoint.setX(newblPx); 
    blPoint.setY(newblPy); 
} 

void Rectangle::display() const 
{ 
    cout << " Location is (" << blPoint.getX() << ", " << blPoint.getY() << "), length is " << length << ", height is " << height << "; Area is " << area() << "; perimeter is " << perimeter() << ", midpoint is located at (" << midPoint().getX() << ", " << midPoint().getY() << ")" << endl; 
} 

Единственная проблема теперь у меня есть с программой является то, что она всегда выдает «Invalid Input Type„ЗАП“следуя по имени. или «остановить», если это сделано », и я не знаю, как это изменить. И когда вы вносите дублированный ответ, как в rec fire и rec fire, он скажет, что rec fire уже используется, а затем продолжает запрашивать этот прямоугольник вместо запроса другого имени. Любая помощь приветствуется!!

+1

Это много кода и не соответствует стилю Q & A этого сайта, попробуйте http://meta.stackexchange.com/questions/tagged/codereview-se – mark

+0

@mark: Осторожно, как вы это называете, это может звучать так, будто вы говорите «попробуйте Meta SO» ([который сделал OP] (http://meta.stackexchange.com/questions/177082/need-help-fixing-minor-issues-in-my-program)) –

+0

@arazan: Mark предлагал вам отметить свой пост и попросить модератора переместить его в Code Review. –

ответ

1

Это неправильно

/* Prompt user for first rectangle or 'stop' */ 
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 

// WHILE user input is invalid 
while (read == false) 
{ 

    // Display "Try again! " 
    cout << "Try again! " << endl; 
    bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 
} 

Вы две переменных чтений, переменные чтения в состоянии в то время как со ссылкой на переменные чтения объявило первой, переменные чтения объявлено второй никогда не используются. Вы хотите это

/* Prompt user for first rectangle or 'stop' */ 
bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 

// WHILE user input is invalid 
while (read == false) 
{ 

    // Display "Try again! " 
    cout << "Try again! " << endl; 
    read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 
} 

Теперь у вас есть только одна переменная чтения. Это объясняет вторую ошибку, которую вы описываете, я думаю.

Другой способ кодирования это как этот

for (;;) 
{ 
    bool read = read_rec(prompt1stName, errorInvalid, errorUsed, inName, list); 
    if (read) 
     break; 
    cout << "Try again! " << endl; 
} 

На мой взгляд, этот вид петли лучше, потому что он не имеет дублированный вызов read_rec, поэтому с этим стилем петли ошибку вы сделали невозможно.

+0

Спасибо! Это исправляло эту ошибку, есть ли у вас какие-либо идеи о том, как исправить ее из вывода errorInvalid, когда она не была неверной ошибкой? Я считаю, что он делает это, потому что это не означает, однако, пользователь не вводит ничего в это время. – arazan

+0

Не уверен, извините. Я бы использовал отладчик для отслеживания того, что происходит с вашей программой шаг за шагом. – john

+0

Спасибо за помощь! Я загружу его прямо сейчас! – arazan