首页 > 解决方案 > 自定义构造函数不会进入 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();

标签: c++loopsfor-loop

解决方案


如果没有找到“phonebook.txt”,getline 将无法工作。

您需要检查同一文件夹中是否存在“phonebook.txt”。

您可以将代码重写为...

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

推荐阅读