gpt4 book ai didi

c++ - 我如何将其读入 Entry fname?

转载 作者:行者123 更新时间:2023-11-28 04:21:41 24 4
gpt4 key购买 nike

我正在尝试将 fname lname 和电话号码 (number) 的用户条目读入私有(private)类中相应命名的函数中。因为我不知道如何直接从输入流 (cin >> get_fname();) 中读取它们,所以我不知道我将如何着手定义如何将它们读入正确的位置

老实说,我不知道该怎么做。

using namespace std;
string getResponse()
{
string response;
cout << endl << "What would you like to do?" << endl;
cout << "Add and entry (a),";
cout << "Sort list (s)," << endl;
cout << "Print the list (p),";
cout << "Find a name (f)," << endl;
cout << "Quit (q)?";

cin >> response;
return response;
}

void printEntry(Entry entry)
{
cout << entry.get_fname() << " " << entry.get_lname() << " " << entry.get_number() << endl;
}

void findName(const list<Entry>& data, string name)
{
for (list<Entry>::const_iterator iter = data.begin(); iter != data.end(); iter++){
if (name == iter->get_lname()){
printEntry(*iter);
}
}
}



Entry readEntry()
{
Entry entry;
cout << "Please enter a first name: ";
string fname;
cin >> fname;
entry.get_fname(fname);
cout << "Please enter a last name: ";
string lname;
cin >> lname;
entry.get_lname(lname);
cout << "Please enter a phone number: ";
string number;
cin >> number;
entry.get_number(number);

return entry;
}

class Entry {
private:

std::string fname;
std::string lname;
std::string number;
public:
std::string get_fname() const;
std::string get_lname() const;
std::string get_number() const;


};

#endif // ENTRY_H_INCLUDED

#include "entry.h"

std::string Entry::get_fname() const {
return fname;
}
std::string Entry::get_lname() const {
return lname;
}
std::string Entry::get_number() const {
return number;
}

最佳答案

你可以

class Entry 中的变量公开并将用户输入加载到其中(您不再需要 getter)

Entry readEntry()
{
Entry entry;
cout << "Please enter a first name: ";
cin >> entry.fname;

cout << "Please enter a last name: ";
cin >> entry.lname;

cout << "Please enter a phone number: ";
cin >> entry.number;

return entry;
}
``````
class Entry {
public:
std::string fname;
std::string lname;
std::string number;
};

class Entry中定义set_*variable*函数:

Entry readEntry()
{
Entry entry;
cout << "Please enter a first name: ";
string fname;
cin >> fname;
entry.set_fname(fname);

cout << "Please enter a last name: ";
string lname;
cin >> entry.lname;
entry.set_lname(lname);

cout << "Please enter a phone number: ";
string number;
cin >> entry.number;
entry.set_number(number);

return entry;
}
``````
class Entry {
public:
std::string fname;
std::string lname;
std::string number;

void set_fname(std::string _fname) { fname = _fname; };
void set_lname(std::string _lname) { lname = _lname; };
void set_number(std::string _number) { number = _number; };
private:
std::string get_fname() const;
std::string get_lname() const;
std::string get_number() const;
};

您使用 get_*variable* 函数返回已设置的变量(我假设),因此这与实际设置这些变量无关。

关于c++ - 我如何将其读入 Entry fname?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com