Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings using == [duplicate]

Code, as shown below, can be complied.

Problem: It always says "Invalid Employee id" even when I enter the correct employee id.
Please tell me why and how to do this correctly.

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

Note: It is going to the else clause all the time.

like image 581
Nishan256 Avatar asked Dec 17 '25 17:12

Nishan256


1 Answers

It's this:

char empid[4];

This is too small as there's no room for a NUL terminator after the id. You could just change it to 5, but then if someone deliberately or accidentally typed a longer string your program may crash (it's called a buffer overrun, and in some situations can allow whoever provides input to hack the account running the program).

Further, == doesn't work for character arrays: you have to use e.g.:

 if (strcmp(empid, "M001") == 0 || strcmp(empid, "A004") == 0 || ...

You would be much better off using a std::string, which will grow to accommodate the actual input (including a NUL terminator though that's not counted in a string's .size()), and works intuitively with ==.


Separately, your...

tot = tot+bonus+bSalary;

...is broken, as bonus may be uninitialised you mustn't read from it in an expression. You can simply remove bonus from the addition above, if it's meant to be 0 for the relevant employees.

like image 136
Tony Delroy Avatar answered Dec 20 '25 08:12

Tony Delroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!