【发布时间】:2020-10-28 03:31:16
【问题描述】:
这里是新手。无法弄清楚为什么我的程序不会进入这个 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();
【问题讨论】:
-
您应该在读取文件之前检查文件是否已打开。
-
“它从未进入 for 循环” - 你知道它是否甚至进入了 while 循环吗?应检查所有输入操作...
if (std::ifstream file{"phonebook.text"}) { while (getline(file, input)) { std::istringstream ss{input}; if (ss >> fname >> lname >> pNumber) { ... } else std::cerr << "unable to parse names and number\n"; } } else std::cerr << "unable to open phonebook.txt\n"; -
array永远不会被初始化。array[i]将表现出未定义的行为,如果它曾经达到。 -
请提供
phonebook.txt的示例或其布局示例,以便您的程序可以轻松地进行全面测试。 -
根据您选择的 IDE,如果
phonebook.txt不存在于正确的位置,getline调用将失败。