所以我正在制作某种存储人们信息的注册表。我的问题是我有一个类,它有一个人的多个 setter 和 getter(名字、出生日期、出生地等)。当我尝试从文本文件中读取信息时,我无法向设置器提供我从文件中获得的参数。
我制作了一个临时文件,我试图找出问题所在,但我真的无处可去。循环无关紧要,如果我想做的事情不在循环中并且文件中只有一行,则问题保持不变
int main(){
std::string firstName;
std::string lastName;
std::string phoneNumber;
std::string birthPlace;
std::string birthDate;
std::string Profession;
Contacts newContact = Contacts();
std::ifstream savedContacts("ContactList.txt");
do{
std::getline(savedContacts, firstName, ';');
std::getline(savedContacts, lastName, ';');
std::getline(savedContacts, phoneNumber, ';');
std::getline(savedContacts, birthPlace, ';');
std::getline(savedContacts, birthDate, ';');
std::getline(savedContacts, Profession, ';');
/*
in this case, this setter doesn't work,
it doesn't get the string stored in firstName,after this,the program
crashes
*/
newContact.setFirstname(firstName);
std::cout<<newContact.getFirstname();
/*
and just to make sure that the reading of the file was successful
if i print out one of these strings, like this, it works perfectly
*/
std::cout<<firstName;
}while(std::getline(savedContacts, firstName));
有趣的是,如果我这样做: newContact.setFirstname("Karen"); 然后 setter 工作得很好,还有我的 getter
这就是我的联系人类中的 setter 和 getter 的样子
std::string Contacts::setFirstname(std::string firstName) {
this->firstName = firstName;
}
std::string Contacts::getFirstname() {
return firstName;
}
这是在 txt 文件中:
John;Wick;1800181819;Paris;11.09.1990;Plumber;
Anthony;Joshua;192918180;Manchester;10.08.1994;Teacher;
// Several issues here:
std::string Contacts::setFirstname(std::string firstName) {
this->firstName = firstName;
}
// Don't return a copy. Setters will usually only *set*
// If you WANT to return the value, you should NOT return a copy
// but a reference or a const reference
// You are copying AGAIN for the argument; take a const reference
// And probably avoid a copy
// Change parameter name and you could spare the this->
// and return a value; you declared a return type but no return statement
// Which means the code you posted doesn't compile
const std::string& Contacts::setFirstname(const std::string& newFirstName)
{
firstName = newFirstName;
return firstName;
}
// Same here, return const reference and let the caller copy only if needed
// And make the getter const so it can work with const Contact
const std::string& Contacts::getFirstname() const {
return firstName;
}
此外,关于您的问题,很可能是在调用 setFirstName 的代码中。你没有提供。请提供最小、完整和可验证的示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句