使用==比较字符串

Nis*_*256 2 c++ string if-statement

可以编写如下所示的代码.

问题:即使我输入正确的员工ID,它也总是说"无效的员工ID".
请告诉我为什么以及如何正确地做到这一点.

#include <iostream>
#include <iomanip>
using namespace std;
char select, js;
char empid[4];
double bSalary, bonus, tot=0.0;
int main()
{
    do
    {
        cout<<"Employee id: ";
        cin>>empid;
        if(empid=="M001" || empid=="A004" || empid == "M002") //these are employee ids
        {   
            cout<<"Job Status: ";
            cin>>js;
            if(js=='P' || js=='C')
            {
                cout<<"Basic Salary: ";
                cin>>bSalary;
                if(bSalary>75000 && js=='P')
                {
                    bonus = bSalary*(20.0/100.0);
                    tot = tot + bonus + bSalary;
                }
                else if(bSalary>75000 && js=='C')
                {
                    bonus = bSalary*(15.0/100.0);
                    tot = tot + bonus + bSalary;
                }
                else
                    tot = tot+bonus+bSalary;
            }
            else
                cout<<"Invalid Job Status"<<endl;
        }
        else
            cout<<"Invalid Employee no"<<endl;
        cout<<"Do you want to continue: ";
        cin>>select;
        cout<<endl;
    }while(select=='y'||select=='Y');
    cout<<"Total cost: "<<setprecision(2)<<setiosflags(ios::fixed)<<tot<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:它始终是该else条款.

Ton*_*roy 11

就是这样:

char empid[4];
Run Code Online (Sandbox Code Playgroud)

这个太小了,因为在id之后没有NUL终结器的空间.您可以将其更改为5,但如果有人故意或意外地键入更长的字符串,您的程序可能会崩溃(它被称为缓冲区溢出,在某些情况下可以允许任何提供输入的人破解运行该程序的帐户).

此外,==不适用于字符数组:您必须使用例如:

 if (strcmp(empid, "M001") == 0 || strcmp(empid, "A004") == 0 || ...
Run Code Online (Sandbox Code Playgroud)

使用a std::string会更好,它会增长以适应实际输入(包括NUL终结器,虽然它不计入strings .size()),并且可以直观地使用==.


另外,你...

tot = tot+bonus+bSalary;
Run Code Online (Sandbox Code Playgroud)

......被打破了,因为bonus你可能没有初始化,你不能在表达中读取它.您可以简单地bonus从上面的添加中删除,如果相关员工的意思是0.