输入错误的文件名时SigSeGV分割故障?
我一直在开发一个新的“狗模拟器”应用程序,并且已经实现了一个功能来加载包含狗及其所有者的现有文件(以及一堆年龄,小吃,零食等)。每当我输入不正确的文件名时,程序都会失败并跳到此部分:
std::string dog_name;
if (owner.dog != nullptr) dog_name = owner.dog->name;
else dog_name = "none";
我实现了以在所有者的“打印”函数中为狗的名称设置默认参数。
我有一个名为“狗”的文件夹,其中我存储了所有保存的文本文件。这是我使用的代码来查找当前的工作目录,并将其与文件名和文件夹目录一起缝合:
std::ifstream load;
std::cout << "\nEnter file name to load: ";
std::getline(std::cin, file_name);
lowercase(file_name); // My own function to set everything to lowercase.
std::filesystem::path cwd = std::filesystem::current_path();
std::string dir = cwd.string();
dir.erase(dir.find("\\cmake"));
dir += "\\dogs\\";
std::string path = dir + file_name + ".txt";
load.open(path);
if (load) {
std::getline(load, dog.name);
load >> dog.age;
...
我怀疑它与我的所有者班级中的指针“ Dog* Dog”有关,但是老实说,我不知道如何解决这个问题。这是我的所有者班级的代码:
class dog;
class owner {
public:
std::string name;
int age;
dog* dog;
// Counters
int poop_counter;
int good_points;
};
任何帮助都将受到赞赏。谢谢你!
编辑: 我设法解决了这个问题。我为狗和所有者添加了默认的构造函数,以解决该问题:
owner::owner() {
this->name = "none";
this->age = 0;
this->dog = nullptr;
this->poop_counter = 0;
this->good_points = 0;
}
I've been working on a new "dog simulator" app and I've implemented a function to load an existing file containing a dog and its owner (along with a bunch of numbers for age, snack-counter etc.). Whenever I enter an incorrect file name, the program fails and jumps to this section:
std::string dog_name;
if (owner.dog != nullptr) dog_name = owner.dog->name;
else dog_name = "none";
I implemented this to set a default parameter to the dog's name in the owner's "print" function.
I have a folder called "dogs" in which I store all saved text files. This is the code I use for finding the current work directory as well as stitching it together with the file name and the folder's directory:
std::ifstream load;
std::cout << "\nEnter file name to load: ";
std::getline(std::cin, file_name);
lowercase(file_name); // My own function to set everything to lowercase.
std::filesystem::path cwd = std::filesystem::current_path();
std::string dir = cwd.string();
dir.erase(dir.find("\\cmake"));
dir += "\\dogs\\";
std::string path = dir + file_name + ".txt";
load.open(path);
if (load) {
std::getline(load, dog.name);
load >> dog.age;
...
I am suspecting that it has something to do with the pointer "dog* dog" in my owner-class, but I honestly have no idea how to work around this. Here is the code for my owner-class:
class dog;
class owner {
public:
std::string name;
int age;
dog* dog;
// Counters
int poop_counter;
int good_points;
};
Any help is appreciated. Thank you!
EDIT:
I managed to fix the problem. I added default constructors for both the dog and the owner which resolved the issue:
owner::owner() {
this->name = "none";
this->age = 0;
this->dog = nullptr;
this->poop_counter = 0;
this->good_points = 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论