自定义构造函数不会进入循环(C++)



这里是新手。不明白为什么我的程序不进入这个循环。我有一个自定义类"联系人"和另一个"电话簿"。电话簿是一个联系人数组,问题在于我创建的构造函数,该构造函数用于使用字符串流读取txt文件中的行。一旦我读取了这些行,将它们分配给变量,并创建了一个Contact对象,我就会放入一个for循环,尝试将它们添加到数组中。当我运行程序时,它从未进入for循环。感谢您的帮助!这可能是一件容易的事情,可以随意地把我撕成碎片,它不会伤害我的感情!

带有for循环的电话簿类,不会进行

#ifndef PHONEBOOK
#define PHONEBOOK
#include <iostream>
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <array>
#include "Contact.h"
using namespace std;
class Phonebook
{
private:
int capacity = 1000000;
int arrSize = 0;
Contact *array;
public:
int count = 0;
Phonebook();
Phonebook(string phonebookfile)
{
string fname;
string lname;
int pNumber;
ifstream file("phonebook.txt");
string input;
**while (getline(file, input))
{
stringstream ss(input);
ss >> fname;
ss >> lname;
ss >> pNumber;
string name;
name = fname + " " + lname;
Contact holder(name, pNumber);
for (int i = 0; i < capacity; i++)
{
array[i] = holder;
arrSize++;
cout << arrSize;
}
}**
};
};
void Phonebook::add(){
string name;
int number;
cout << "Enter Name:";
cin >> name;
cout << "Enter Number:";
cin >> number;
Contact holder(name, number);
array[arrSize] = holder;
}
#endif

联系人类别

#ifndef CONTACT
#define CONTACT
#include <string>
#include <iostream>
using namespace std;
class Contact
{
private:
string name;
int pNumber;
public:
Contact();
Contact(string name, int pNumber)
{
this->name = name;
this->pNumber = pNumber;
}
};
#endif

我主要是如何调用构造函数的:

#include <string>
#include "Contact.h"
#include "Phonebook.h"
using namespace std;
int main()
{
Phonebook phonebook("phonebook.txt");
phonebook.add();

如果;电话簿.txt";找不到,getline将不起作用。

您需要检查";电话簿.txt";存在于同一文件夹中。

你可以将代码重写为…

ifstream file("phonebook.txt");
if(!file){ 
cerr << "The file couldn't be open!n"; 
exit(1);
}

最新更新