如何解决为什么在获取此变量时出现分段错误?
我正在从文件中将名称作为字符串提取,创建一个Person *p
对象,并将其放入数组中。
然后在数组中搜索一个名称,但是当我尝试获取该名称时,出现了分段错误。
为什么会出现这种细分错误,我该怎么办才能解决?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f,string l,string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
创建数组。
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file,line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList,count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[],int size)
{
string f,l,n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f,n);
arr[i] = p;
delete p;
}
}
搜索,这是有麻烦的部分。我尝试了一些其他操作,包括创建2个Persons并比较它们的零件,但是无论何时进入.h,它都无法返回名称。
if (uInput == "s" || uInput == "S")
{ //To Search
string f,l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f,"");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("","","");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。