我有一个需要为学校完成的练习,这让我感到困惑。我只需要提示正确的方向即可,因为这对我来说没有意义。
在 Employee 类中添加一个成员函数:
void Employee::format(char buffer[], int buffer_maxlength)
成员函数应该用员工的姓名和薪水填充缓冲区。确保不要超出缓冲区。它可以保存 buffer_maxlength 个字符,不包括 '\0' 终止符。
我没有得到的是传递给函数的参数是什么。不应该传递名称,然后将其输入缓冲区吗?或者,函数不应该不接受任何参数并填充缓冲区吗?如果缓冲区是一个参数,我如何填充它?
这里很困惑。
还没有开始编码,因为我还不明白这个练习。
不需要任何人为我编写程序,只需要提示这里发生了什么。
谢谢。
编辑:这是我到目前为止的代码,它似乎有效。我不确定的一件事是缓冲区溢出。由于我无法调整缓冲区的大小,我是否应该将其设置为我知道现有数据不会超出的大小?这似乎效率低下,但不知道还能做什么。
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string.h>
#pragma warning(disable : 4996) // had to include this for the strcpy function, not sure why
using namespace std;
/**
A basic employee class that is used in many examples
in the book "Computing Concepts with C++ Essentials"
*/
class Employee
{
public:
/**
Constructs an employee with empty name and no salary.
*/
Employee();
/**
Constructs an employee with a given name and salary.
@param employee_name the employee name
@param initial_salary the initial salary
*/
Employee(string employee_name, double initial_salary);
/**
Sets the salary of this employee.
@param new_salary the new salary value
*/
void set_salary(double new_salary);
/**
Gets the salary of this employee.
@return the current salary
*/
double get_salary() const;
/**
Gets the name of this employee.
@return the employee name
*/
string get_name() const;
void format(char buffer[], int buffer_maxlength);
private:
string name;
double salary;
char buffer;
};
Employee::Employee()
{
salary = 0;
}
Employee::Employee(string employee_name, double initial_salary)
{
name = employee_name;
salary = initial_salary;
}
void Employee::set_salary(double new_salary)
{
salary = new_salary;
}
double Employee::get_salary() const
{
return salary;
}
string Employee::get_name() const
{
return name;
}
void Employee::format(char buffer[], int buffer_maxlength)
{
string temp_name;
//string space = " ";
char terminator = '\0';
double input_salary = salary;
string s;
stringstream output_salary;
output_salary << input_salary;
s = output_salary.str();
temp_name = name.c_str() + s + terminator;
strcpy(buffer, temp_name.c_str());
cout << buffer << endl;
}
int main()
{
const int BUFFER_SIZE = 100;
char input_buffer[BUFFER_SIZE];
string temp_string;
string space = " ";
Employee bob_buffer("Buffer, Bob", 100000);
bob_buffer.format(input_buffer, BUFFER_SIZE);
system("pause");
return 0;
}
编辑:使用 strncpy 而不是 strcpy 来防止溢出