这个程序应该允许我输入一个字符串,并允许我按姓名、工资率或 ID 搜索员工。但是,由于 strlen()
函数出错,它不会编译。
我得到的错误是:
main.cpp:88:39: error: cannot convert 'double' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'
我该如何修复这个错误?
#include <iostream>
using namespace std;
struct Employee
{
int idNum;
double payRate;
char firstName, lastName;
};
int main()
{
int error;
const int SIZE = 5;
Employee employee[SIZE];
for (int k = 0; k < SIZE; ++k)
{
employee[k].idNum = 0;
employee[k].payRate = 0;
}
for (int count = 0; count < SIZE; ++count)
{
error = 0;
cout << "Enter the employee's id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
while (error == 1)
{
cout << "Invalid entry. Please enter a new id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
error = 0;
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
}
cout << "Enter the employee's pay rate " << endl;
cin >> employee[count].payRate;
cout << "Enter the employee's first name " << endl;
cin >> employee[count].firstName;
cout << "Enter the employee's last name " << endl;
cin >> employee[count].lastName;
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
}
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
if (choice == 1)
{
int idNumC;
cout << "Enter an id number ";
cin >> idNumC;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].idNum == idNumC)
cout << employee[count].idNum;
}
}
if (choice == 2)
{
string name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for (int count = 0; count < SIZE; ++count)
{
if (strcmp(employee[count].lastName, name) == 0)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
if (choice == 3)
{
int nam;
cout << "Enter the employee's last name " << endl;
cin >> nam;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].payRate == nam)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
}
最佳答案
employee[count].lastName
是一个字符,而不是一个 c 字符串(空终止字符数组)。此外,name
是一个 std::string
,而不是一个 c 字符串。
它们必须是同一类型才能比较,所以选择一个类型。如果你想让 lastName
成为 std::string
那么你可以这样做
if( employee[count].lastName == name )
否则,如果您将 lastName
设为 C 字符串,则您也需要将 name
设为一个,因此您可以:
if (strcmp(employee[count].lastName, name.c_str()) == 0)
关于c++ - 程序无法编译,使用带有结构对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204092/