c++ 函数setHeight和函数setWeight的逻辑异常输出错误[已关闭]

ilmyapht  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(112)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
16小时前关门了。
Improve this question
当我输入这个:

Anne Niebuhr 2 15 1996 -104.9 5.7
y
Jesse Choi 12 4 1962 161.9 5.11
n

我得到这个逻辑错误:

我想打印此输出

Person.cpp中,我在函数setHeight和函数setWeight上使用了try块,然后将其抛给PersonExceptions.cpp以返回输入异常错误。当我运行程序时,它打印出无效语句和无效输入。我如何使程序不打印出|Anne|Niebuhr|Febraury 15, 1996| 5.7 feet| 0 lbs|
main.cpp

#include <iostream>
#include <vector>

#include "Date.h"
#include "Person.h"
#include "DateException.h"
#include "PersonExceptions.h"

int main() {
    std::string firstName;
    std::string lastName;
    int birthMonth;
    int birthDay;
    int birthYear;
    float height;
    float weight;
    char answer = 'y';

    std::vector<CIST2362::Person> personDatabase; // vector of Person Objects

    // input person objects
    // You must catch exceptions properly
    while (toupper(answer) == 'Y') {
        std::cin >> firstName;
        std::cin >> lastName;
        std::cin >> birthMonth;
        std::cin >> birthDay;
        std::cin >> birthYear;
        std::cin >> weight;
        std::cin >> height;

       // place person objects into vector
       
       
       //
       CIST2362::Person data(firstName,lastName,birthDay,birthMonth,birthYear,height,weight);
    personDatabase.push_back(data);

        std::cin >> answer;
    }

    // output the person objects

    for(int i=0;i<personDatabase.size();i++)
    {
        CIST2362::Person data=personDatabase[i];
        std::cout<<data.toString();
    }
    return 0;
}

Person.cpp

#include <sstream>
#include <iomanip>

#include "Person.h"
#include "PersonExceptions.h"

namespace CIST2362 {
    const std::string &Person::getFirstName() const {
     

        //  return firstName value
        return firstName;
    }

    void Person::setFirstName(const std::string &firstName) {
      
        // points to firstName
        this->firstName = firstName;
    }

    const std::string &Person::getLastName() const {
        
        //  return lastName value
        return lastName;
    }

    void Person::setLastName(const std::string &lastName) {
        
        // points to firstName
        this->lastName = lastName;
    }

    const Date &Person::getBirthdate() const {
       
         //return birthdate value
        return this->birthdate;
    }

    void Person::setBirthdate(const Date &birthdate) {
        
        // points to firstName
       this->birthdate=birthdate;
    }

    float Person::getHeight() const {
       
        //return height value
        return this->height;
    }

    void Person::setHeight(float height) {
       
        // try if height are less than 0
        try{
            if(height<0){
                                                 // throws char

                badHeight w;
                throw w;

            }
            else{
                this->height = height;

            }

        }
        catch(std::exception& e){
        std::cout<<e.what();
        }
    }

    float Person::getWeight() const {
        
        //return weight value
        return this->weight;
    }

    void Person::setWeight(float weight) {

      

        // try if weight are less than 0
        try{
            if(weight<0){
                                 // throws char

                badWeight w;
                throw w;

            }
            else{
                this->weight = weight;

            }

        }
                // catch error

        catch(std::exception& e){
        std::cout<<e.what();
        }
    }

    Person::Person(const std::string &firstName, const std::string &lastName, int birthday,
                   int birthmonth, int birthyear, float height, float weight) : firstName(firstName),
                   lastName(lastName), birthdate(birthday, birthmonth, birthyear) {
       
        // returns the input objects

    this->setFirstName(firstName);
    this->setLastName(lastName);
    this->setHeight(height);
    this->setWeight(weight);
    this->birthdate.setDay(birthday);
    this->birthdate.setMonth(birthmonth);
    this->birthdate.setYear(birthyear);
    }


       
  std::string Person::toString()const{
  std::stringstream heightSS, weightSS;
  heightSS << height;
  weightSS << weight;

  // formats the inputs
  return "|"+firstName + "|" + lastName + "|" + birthdate.getDateLong() + "| " + heightSS.str() + " feet" + "| " + weightSS.str() + " lbs" + "|\n";
}

}
`

`#ifndef LESSON_5_PROGRAMMING_ASSIGNMENT_PERSON_H
#define LESSON_5_PROGRAMMING_ASSIGNMENT_PERSON_H

#include <string>
#include "Date.h"

namespace CIST2362 {

    class Person {
    private:
        std::string firstName;
        std::string lastName;
        Date birthdate;
        float height;
        float weight;

    public:
        Person(const std::string &firstName, const std::string &lastName, int birthday, int birthmonth,
               int birthyear, float height, float weight);

        const std::string &getFirstName() const;

        void setFirstName(const std::string &firstName);

        const std::string &getLastName() const;

        void setLastName(const std::string &lastName);

        const Date &getBirthdate() const;

        void setBirthdate(const Date &birthdate);

        float getHeight() const;

        void setHeight(float height);

        float getWeight() const;

        void setWeight(float weight);

        std::string toString()const;
    };

} 
#endif

Date.cpp

#include "Date.h"
#include "DateException.h"
#include <sstream>

namespace CIST2362 {

    Date::Date() {
        

        //create default constructer

        setNames();
        setDay(0);
        setMonth(0);
        setYear(1900);

    }

    Date::Date(int m, int d, int y) {
      

     //create constructer

        setNames();
        setDay(d);
        setMonth(m);
        setYear(y);
}



    void Date::setNames() {
        names[1] = "January";
        names[2] = "Febraury";
        names[3] = "March";
        names[4] = "April";
        names[5] = "May";
        names[6] = "June";
        names[7] = "July";
        names[8] = "August";
        names[9] = "September";
        names[10] = "October";
        names[11] = "November";
        names[12] = "December";
    }

    void Date::setMonth(int m) {
    

        // try if months are less than 0 or greater than 12

        try{

            if(m<0){

                InvalidMonth w;
                throw w;
            }else{

                month=m;
            }

        }
        // catch error
         catch(std::exception& e) {
            std::cout<<e.what();
        }
    }

    void Date::setDay(int d) {
     

                // try if days are less than 0 or greater than 31

         try{

            if(d<0){
                // throws char
                InvalidDay w;
                throw w;
            }else{

                day=d;
            }

        }
                // catch error

         catch(std::exception& e) {
            std::cout<<e.what();
        }
    }

    void Date::setYear(int y) {
        
        // try if years are less than 0

        try{

            if(y<0){
                 // throws char
                InvalidYear w;
                throw w;
            }else{

                year=y;
            }

        }
        // catch error
         catch(std::exception& e) {
            std::cout<<e.what();
        }
    }

    std::string Date::getDateShort() {
    

        //declares stringstream varablies
        std::stringstream dd, mm, yy;

        //turns day, mouth, year it
        dd<<day;
        mm<<month;
        yy<<year;

        //gets dd, mm, yy

std::string s=mm.str()+"/"+dd.str()+"/"+yy.str();
        return s;
    }

    std::string Date::getDateLong()const{
        
        //declares stringstream varablies

        std::stringstream dd, mm, yy;
        //gets dd, mm, yy

         dd<<day;
        mm<<month;
        yy<<year;
          //converts  mm, to string
std::string s=names[month]+" "+dd.str()+", "+yy.str();

        return s;
    }

}

DateException.cpp

#ifndef LESSON_5_PROGRAMMING_ASSIGNMENT_DATE_H
#define LESSON_5_PROGRAMMING_ASSIGNMENT_DATE_H
#include <iostream>
#include <string>

namespace CIST2362 {

    // Constants
    const int NUM_MONTHS = 13;

    class Date {
    private:
        int month;
        int day;
        int year;

        // An array of strings to hold
        // the names of the months
        std::string names[NUM_MONTHS];

        // Private member function to assign
        // the month names to the names array
        void setNames();

    public:
        // Constructors
        Date();
        Date(int, int, int);

        // Mutators
        void setMonth(int m);
        void setDay(int d);
        void setYear(int y);

        // Functions to print the date
        std::string getDateShort();
        std::string getDateLong()const;
    };

}

#endif
`
**DateException.h**

`#ifndef LESSON_5_PROGRAMMING_ASSIGNMENT_DATEEXCEPTION_H
#define LESSON_5_PROGRAMMING_ASSIGNMENT_DATEEXCEPTION_H
#include <exception>

namespace CIST2362 {

    // Exception classes
class InvalidDay: public std::exception {
public:
    
    
    // calls exception error function
    const char * what() const throw();
};

class InvalidMonth: public std::exception {
public:
  
    // calls exception error function
    const char * what() const throw() ;
};

class InvalidYear: public std::exception {
public:
// calls exception error function
   
    const char * what() const throw();
};

}

#endif

PersonExceptions.cpp

#include "PersonExceptions.h"

namespace CIST2362 {

  
    const char * badHeight::what() const throw() {
                // catchs char and gives exception error

            return "Invalid Height assigned - must be a positive number\n";
        }

                        // catchs char and gives exception error

         const char * badWeight::what() const throw(){
            return "Invalid Weight assigned - must be a positive number\n";
        }

}

`
`#include "PersonExceptions.h"

namespace CIST2362 {

    
    const char * badHeight::what() const throw() {
                // catchs char and gives exception error

            return "Invalid Height assigned - must be a positive number\n";
        }

                        // catchs char and gives exception error

         const char * badWeight::what() const throw(){
            return "Invalid Weight assigned - must be a positive number\n";
        }

}
`
**PersonExceptions.h**

`#ifndef LESSON_5_PROGRAMMING_ASSIGNMENT_PERSONEXCEPTIONS_H
#define LESSON_5_PROGRAMMING_ASSIGNMENT_PERSONEXCEPTIONS_H

#include <exception>

namespace CIST2362 {

    class badHeight: public std::exception {
    public:
        
            // calls exception error function

        const char * what() const throw() ;
    };

    class badWeight: public std::exception {
    public:
    
       
 // calls exception error function

        const char * what() const throw() ;
    };

} 

#endif
vh0rcniy

vh0rcniy1#

  • 必须正确捕获异常 *

你没有这么做,这是你的代码

void Person::setHeight(float height) {
   
    // try if height are less than 0
    try {
        if (height<0) {
            badHeight w;
            throw w;
        }
        else {
            this->height = height;
        }
    }
    catch (std::exception& e) {
        std::cout<<e.what();
    }
}

setWeight方法中抛出并捕获异常,而应该在setWeight(错误发生的地方)中抛出异常,并捕获异常**,在这里您希望从错误中恢复**,在您的情况下,这将是在您要求用户输入更多内容之前。
因此将上面的代码更改为

void Person::setHeight(float height) {
   
    if (height<0) {
        badHeight w;
        throw w;
    }
    else {
        this->height = height;
    }
}

在这个版本中,您只需抛出错误,没有捕获,因为此代码不知道您希望如何从错误中恢复。
把你的主循环改成这样

// You must catch exceptions properly
while (toupper(answer) == 'Y') {
    std::cin >> firstName;
    std::cin >> lastName;
    std::cin >> birthMonth;
    std::cin >> birthDay;
    std::cin >> birthYear;
    std::cin >> weight;
    std::cin >> height;

    // place person objects into vector UNLESS AN EXCEPTION OCCURS
    try {
        CIST2362::Person data(firstName, lastName, birthDay, 
            birthMonth, birthYear, height, weight);
        personDatabase.push_back(data);
    }
    catch (std::exception& e) {
        std::cout << e.what() << '\n';
    }
    std::cin >> answer;
}

这就是你捕获的地方,注意,这样如果抛出异常,那么没有东西被添加到person数据库中,所以你不会打印出错误的条目。

相关问题