how do i input another string in same data member for another object in c++?

79 views Asked by At

//Program for displaying total salary of employees

#include <iostream>
#include <cstdio>
using namespace std;
[enter image description here][1]
    class employee
    {
    char ename[25];
    int emp_id, basic_sal;
    float da, hra, total;
    public:
        int input();
        int calculate();
        int output();
};

int main()
{
    employee e1;
    employee e2;
    employee e3;
    cout <<"\n Enter details of first employee\n";
    e1.input();
    e1.calculate();
    cout <<"\n Enter details of Seond employee\n";
    e2.input();
    //fflush(stdin);
    e2.calculate();
    cout <<"\n Enter details of Third employee\n";
    e3.input();
    //fflush(stdin);
    e3.calculate();
    e1.output();
    e2.output();
    e3.output();
    return 0;
}
int employee::input()
{
    cout <<"Enter the name of employee\n";
    cin.clear();
    fflush(stdin);
    cin.getline(ename, 49);
    cout <<"Enter employee id\n";
    cin >>emp_id;
    cout <<"Enter the basic salary\n";
    cin >>basic_sal;
    return 0;
}
int employee::calculate()
{
    int pda, phra;
    cout <<"Enter DA (percentage)\n";
    cin >>pda;
    cout <<"Enter HRA (Percentage)\n";
    cin >>phra;
    da = (basic_sal*pda)/100;
    hra = (basic_sal*phra)/100;
    total = basic_sal + da + hra;
    return 0;
}
int employee::output()
{
    cout <<"Name of Employee - " <<ename <<"\n" <<"Employee ID - ";
    cout <<emp_id <<"\n" <<"Basic Salary - " <<basic_sal <<"\n"; 
    cout <<"Da - " <<da <<"\n" <<"hra - " <<hra  << "\n"; 
    cout <<"Total Salary - " <<total <<"\n\n\n"; 
    return 0;
}

In the above code for object e1 the input is fine but it skips variable "ename" for object "e2" and object "e3". I cleared buffer using "fflush(stdin);". What would be the problem? I am using g++ compiler and geany editor. There are no compilation errors in the code.

1

There are 1 answers

0
Miroslav Mares On BEST ANSWER

Are the details of each employee entered on new line? If so, you must use something like

cin >> ws;

at the beginning of employee::input() function. It will skip all whitespaces until a first non-whitespace character is found (which is left intact).

Now, the cin >> phra loads some number from stdin (I presume the last number on the line), but does not consume the newline character after it. Therefore, it is left there for the first cin.getline() call in employee::input(), which will read only this newline, so the ename will be empty.