如何调试这个C++类出了什么问题?

How to debug what's wrong with this C++ class?

本文关键字:什么 问题 C++ 何调试 调试      更新时间:2023-10-16
#include<iostream>
using namespace std;
class emp
{
    public:
                int en;
                char name[10],des[10];
void get()
{
    cout<<"enter emp no.";
    cin>>en;
    cout<<"enter emp name";
    cin>>name;
    cout<<"enter designation";
    cin>>des;
}
};
class salary : public emp
{
public:
    float bp,hra,da,pf,np;
    void get1()
    {
    cout<<"enter basic pay";
    cin>>bp;
    cout<<"enter domestic allowance";
    cin>>da;
    cout<<"enter profit fund";
    cin>>pf;
    cout<<"enter human resource admittance";
    cin>>hra;
    }
    void calculate()
    {
        np=bp+da+hra-pf;
    }
    void display()
    {
        cout<<en<<"t"<<name<<"t"<<des<<"t"<<da<<"t"<<pf<<"t"<<np<<"n";
    }
    };
    int main()
    {
    salary s[10];
    int i,n;
    char ch;
    cout<<"enter the no. of employees";
    cin>>n;
    for(i=0;i<=n;i++)
    {
     s[i].get();
     s[i].get1();
     s[i].calculate();
    }
    cout<<"n eno. t ename t des t bp t hra t da t pf t np n";
    for(i=0;i<=n;i++)
    {
     s[i].display();
    }
    return 0;
    } 

cin>>des[10];读取标准输入的一个(单个)字符,并尝试将其写入des[10]。不幸的是,您将des定义为具有10个字符,因此只有des[0]des[9]是有效的,因此当它尝试写入des[10]时,您会得到未定义的行为。

我的猜测是您可能想要更多类似的东西:

cin.getline(des, 10);

这试图从cin中读取10个字符的最多10个字符,并将其写入des(并确保其nul终止)。

当然,同样的是name

完成此操作后,您可能想忘记上述所有内容,将namedes同时定义为std::string s。然后,您可以使用std::getline(std::cin, name);。因此,您不必指定最大尺寸;该字符串将扩展到用户输入的数量。

而不是名称[10]和des [10],使用cin>>名称和cin>> des