任务与指标 C++

huangapple go评论71阅读模式
英文:

Task with indicators c++

问题

我有一个任务要做:

给定以下结构:

struct employee { string first name, char* position; double salary; char gender;};

编写一个函数,创建并填充包含n个雇员的数组。员工数量仅在运行程序后给出。请记住检查数据的有效性:first name和position字段只包含字母;salary字段是大于零的值;gender字段只接受两个值,'K'或'M'。

加载各个值,直到用户输入正确的数据为止。

将n的值和指向数组的指针作为函数参数传递。

编写一个程序来测试该函数。

我写了下面的代码。但我完全无法运行它。首先,我使用了函数"strcpy",但Visual Studio将其视为错误并建议更改为strcpy_s,我不确定如何使用它。您能看一下我的代码,并指出应该如何更改以使其工作吗?

编辑:最终,我需要获取在程序中指定的员工及其数据。

#include <iostream>
#include <string>
using namespace std;

struct employee {
    string first_name;
    char* position;
    double salary;
    char gender;
};

void createEmployees(int n, employee* &employees) {
    employees = new employee[n]; // 为雇员数组分配内存
    
    for (int i = 0; i < n; i++) {
        cout << "Employee " << i + 1 << ":" << endl;
        
        // 输入first name
        string first_name;
        while (true) {
            cout << "First name: ";
            cin >> first_name;
            bool valid = true;
            for (char c : first_name) {
                if (!isalpha(c)) {
                    valid = false;
                    break;
                }
            }
            if (valid) {
                employees[i].first_name = first_name;
                break;
            } else {
                cout << "Invalid input. Please enter only letters." << endl;
            }
        }
        
        // 输入position
        string position;
        while (true) {
            cout << "Position: ";
            cin >> position;
            employees[i].position = new char[position.length() + 1];
            bool valid = true;
            for (char c : position) {
                if (!isalpha(c)) {
                    valid = false;
                    break;
                }
            }
            if (valid) {
                strcpy(employees[i].position, position.c_str());
                break;
            } else {
                cout << "Invalid input. Please enter only letters." << endl;
            }
        }
        
        // 输入salary
        double salary;
        while (true) {
            cout << "Salary: ";
            cin >> salary;
            if (salary > 0) {
                employees[i].salary = salary;
                break;
            } else {
                cout << "Invalid input. Please enter a value greater than zero." << endl;
            }
        }
        
        // 输入gender
        char gender;
        while (true) {
            cout << "Gender (M/F): ";
            cin >> gender;
            if (gender == 'M' || gender == 'K') {
                employees[i].gender = gender;
                break;
            } else {
                cout << "Invalid input. Please enter 'M' or 'K'." << endl;
            }
        }
    }
}

int main() {
    int n;
    cout << "有多少员工? ";
    cin >> n;
    
    employee* employees;
    createEmployees(n, employees);
    
    // 打印员工详细信息
    for (int i = 0; i < n; i++) {
        cout << "员工 " << i + 1 << ":" << endl;
        cout << "First name: " << employees[i].first_name << endl;
        cout << "Position: " << employees[i].position << endl;
        cout << "Salary: " << employees[i].salary << endl;
        cout << "Gender: " << employees[i].gender << endl;
        cout << endl;
    }
    
    // 释放雇员数组的内存
    for (int i = 0; i < n; i++) {
        delete[] employees[i].position;
    }
    delete[] employees;
    
    return 0;
}
英文:

I have one task to do:

> The following structure is given:
>
>
&gt; struct employee { string first name, char* position; double salary; char gender;};
&gt;

>
> Write a function that creates and populates an array of n employees. The number of employees is only given after running the program. Remember to check the validity of the data: the fields first name and position consist of letters only; the salary field is a value greater than zero; the gender field takes only two values, 'K' or 'M'.
>
> Load the individual values until the user enters the correct data.
>
> Pass the value of n and a pointer to the array as function parameters.
>
> Write a programme to test the function.

I wrote the code below. But I can't run it at all. Got errors: 1st of all I used function "strcpy" and visual studio point this as an error and indicate to change it to strcpy_s which I am not sure how to use (?). Could you look at my code and indicate what to do better/change so it would work?

EDIT: As a result, I need to obtain the listed employees with their data specified in the programme.

#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;
struct employee {
string first_name;
char* position;
double salary;
char gender;
};
void createEmployees(int n, employee* &amp;employees) {
employees = new employee[n]; // allocate memory for the array of employees
for (int i = 0; i &lt; n; i++) {
cout &lt;&lt; &quot;Employee &quot; &lt;&lt; i + 1 &lt;&lt; &quot;:&quot; &lt;&lt; endl;
// input first name
string first_name;
while (true) {
cout &lt;&lt; &quot;First name: &quot;;
cin &gt;&gt; first_name;
bool valid = true;
for (char c : first_name) {
if (!isalpha(c)) {
valid = false;
break;
}
}
if (valid) {
employees[i].first_name = first_name;
break;
} else {
cout &lt;&lt; &quot;Invalid input. Please enter only letters.&quot; &lt;&lt; endl;
}
}
// input position
string position;
while (true) {
cout &lt;&lt; &quot;Position: &quot;;
cin &gt;&gt; position;
employees[i].position = new char[position.length() + 1];
bool valid = true;
for (char c : position) {
if (!isalpha(c)) {
valid = false;
break;
}
}
if (valid) {
strcpy(employees[i].position, position.c_str());
break;
} else {
cout &lt;&lt; &quot;Invalid input. Please enter only letters.&quot; &lt;&lt; endl;
}
}
// input salary
double salary;
while (true) {
cout &lt;&lt; &quot;Salary: &quot;;
cin &gt;&gt; salary;
if (salary &gt; 0) {
employees[i].salary = salary;
break;
} else {
cout &lt;&lt; &quot;Invalid input. Please enter a value greater than zero.&quot; &lt;&lt; endl;
}
}
// input gender
char gender;
while (true) {
cout &lt;&lt; &quot;Gender (M/F): &quot;;
cin &gt;&gt; gender;
if (gender == &#39;M&#39; || gender == &#39;K&#39;) {
employees[i].gender = gender;
break;
} else {
cout &lt;&lt; &quot;Invalid input. Please enter &#39;M&#39; or &#39;K&#39;.&quot; &lt;&lt; endl;
}
}
}
}
int main() {
int n;
cout &lt;&lt; &quot;How many employees? &quot;;
cin &gt;&gt; n;
employee* employees;
createEmployees(n, employees);
// print employee details
for (int i = 0; i &lt; n; i++) {
cout &lt;&lt; &quot;Employee &quot; &lt;&lt; i + 1 &lt;&lt; &quot;:&quot; &lt;&lt; endl;
cout &lt;&lt; &quot;First name: &quot; &lt;&lt; employees[i].first_name &lt;&lt; endl;
cout &lt;&lt; &quot;Position: &quot; &lt;&lt; employees[i].position &lt;&lt; endl;
cout &lt;&lt; &quot;Salary: &quot; &lt;&lt; employees[i].salary &lt;&lt; endl;
cout &lt;&lt; &quot;Gender: &quot; &lt;&lt; employees[i].gender &lt;&lt; endl;
cout &lt;&lt; endl;
}
// deallocate memory for the array of employees
for (int i = 0; i &lt; n; i++) {
delete[] employees[i].position;
}
delete[] employees;
return 0;
}

答案1

得分: 1

我在你的帖子中看到一个问题:

但我根本无法运行它。出现了错误:首先,我使用了函数“strcpy”,但Visual Studio将其标记为错误,并建议将其更改为strcpy_s

为了绕过这个问题(正如Visual Studio建议的,就在错误旁边)

错误 C4996: 'strcpy': 此函数或变量可能不安全。考虑使用strcpy_s。要禁用弃用警告,请使用_CRT_SECURE_NO_WARNINGS。请参阅在线帮助了解详情。

你可以在文件的顶部添加以下内容:

#define _CRT_SECURE_NO_WARNINGS

另外,为了避免在用户输入无效时出现内存泄漏(正如在上面的评论中指出的),我建议使用 strdup() 来复制你的字符串。请注意,你需要使用 free() 来释放它,而不是使用 delete

你还有一个更大的问题,如果输入double salary时输入非数字,将会导致无限循环。你的cin会进入“坏”状态,并且不会再接受任何输入。

要解决这个问题,你需要使用 cin.ignore();请参考 https://stackoverflow.com/questions/25475384/when-and-why-do-i-need-to-use-cin-ignore-in-c 以获取详细说明。

英文:

I see one question in your post:

> But I can't run it at all. Got errors: 1st of all I used function "strcpy" and visual studio point this as an error and indicate to change it to strcpy_s

To bypass this (as Visual Studio suggests right next to that error)

> error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

, you can add this at the top of your file:

#define _CRT_SECURE_NO_WARNINGS

Alternatively, and to avoid memory leak in case of invalid user entry (as was pointed in the comments above), I would use strdup() to duplicate your string. Note that you would have to free() it instead of delete.

You do have a bigger problem that will cause an infinite loop if you enter non-number for the double salary. Your cin will go into a bad state and won't accept any more input.

To fix that, you need to use cin.ignore(); see https://stackoverflow.com/questions/25475384/when-and-why-do-i-need-to-use-cin-ignore-in-c for esplanation.

huangapple
  • 本文由 发表于 2023年2月24日 03:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定