The main problem on your side is inadvertent use of the assignment operator =
instead of the intended comparison ==
.
On the language's side this common problem was enabled via two risk-enhancing features inherited from original C, namely that a formal condition accepts any object with a conversion to bool
, and that, in support of multi-assignments, assignment is an expression rather than a statement.
You were lucky to compile with a compiler and options that produced a warning about it: such warnings are not guaranteed.
A guaranteed way to instead get an error is to let the left hand side be an expression that can't be assigned to, e.g.
- use
const
liberally, wherever it makes sense.
In the given case, instead of
void Employees::delete_employee()
{
int employee_number;
cout<<"\n..."<<endl<<endl;
cout<<"Give me the number:";
cin>>Employee_number;
for(std::vector<EmployeeStruct>::size_type i = 0; i != lista.size(); i++)
{
if (employee_number = lista[i].Employee_number)
{
lista.erase(lista.begin() + i);
}
}
cout<<"..."<<endl<<endl;
cout<<"--------------------------------"<<endl;
}
you can do the safer
auto fail() -> bool ...;
auto line_from( istream& stream )
-> string
{
string line;
getline( stream, line )
or fail();
return line;
}
void Employees::delete_employee()
{
cout<<"\n..."<<endl<<endl;
cout<<"Give me the number:";
int const Employee_number = to_string( line_from( cin ) );
for(std::vector<EmployeeStruct>::size_type i = 0; i != lista.size(); i++)
{
if (employee_number == lista[i].Employee_number)
{
lista.erase(lista.begin() + i);
}
}
cout<<"..."<<endl<<endl;
cout<<"--------------------------------"<<endl;
}
This code will not compile at all if ==
is used instead of =
, and as a bonus using getline
helps to avoid many common problems with input of values from cin
.
A different kind of fix is to redefine if
via a macro, or to define a macro that expands to a safe use of if
. The first is technically possible but formally Undefined Behavior if any standard library header is included, which is usually the case. The second is a severe (usually unacceptable) uglification of the code, and will make maintenance a nightmare. As I recall something like that was once done for one of the Unix shells. Since nobody but the original programmer understood any of the code, it had a short life.