【问题标题】:how do i input another string in same data member for another object in c++?如何在 C++ 中为另一个对象在同一数据成员中输入另一个字符串?
【发布时间】:2017-09-10 07:53:51
【问题描述】:

//员工工资总额显示程序

#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;
}

在对象 e1 的上述代码中,输入很好,但它跳过了对象“e2”和对象“e3”的变量“ename”。我使用“fflush(stdin);”清除了缓冲区。会有什么问题? 我正在使用 g++ 编译器和 geany 编辑器。 代码中没有编译错误。

【问题讨论】:

标签: c++ cin fflush


【解决方案1】:

是否在新行中输入了每个员工的详细信息?如果是这样,你必须使用类似的东西

cin >> ws;

employee::input() 函数的开头。它将跳过所有空格,直到找到第一个非空格字符(保持不变)。

现在,cin &gt;&gt; phrastdin 加载了一些数字(我假设该行的最后一个数字),但不消耗它后面的换行符。因此,它留在那里供employee::input() 中的第一个cin.getline() 调用使用,它将只读取此换行符,因此ename 将为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多