c++ - 自定义构造函数不会进入 for 循环(C++)
问题描述
新手来了 无法弄清楚为什么我的程序不会进入这个 for 循环。我有一个自定义类的“联系人”和另一个“电话簿”。电话簿是一个联系人数组,问题在于我创建的构造函数,该构造函数使用 stringstream 从 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
我如何在 main 中调用构造函数:
#include <string>
#include "Contact.h"
#include "Phonebook.h"
using namespace std;
int main()
{
Phonebook phonebook("phonebook.txt");
phonebook.add();
解决方案
如果没有找到“phonebook.txt”,getline 将无法工作。
您需要检查同一文件夹中是否存在“phonebook.txt”。
您可以将代码重写为...
ifstream file("phonebook.txt");
if(!file){
cerr << "The file couldn't be open!\n";
exit(1);
}
推荐阅读
- xml - 错误:无法找到或加载主类 com.sun.tools.internal.xjc.XJCFacade
- function - 使用变量时真正发生了什么?
- matlab - 防止彩条在 MATLAB 中调整图像大小
- angular - 如何在 Angular 的 Rxjs 6 中使用运算符
- javascript - javascript中表单提交的返回方法
- android - 生成请求代码时未显示通知
- ios - 在 iOS 和 macOS 玩家之间使用 GameCenter 启用多人游戏
- bash - 简单的 shell 脚本程序中的错误
- javascript - 为什么带有 Vue.js 的 Webpack 会产生这么大的构建文件?
- php - PHP DateTime diff 返回错误的差异