我在 C++、编码和一般知识方面还是很新,所以请多多包涵。
所以最近在我的计算机科学课上,我被要求制作一个充当电话簿的程序,能够保存不同联系人的信息,例如他们的姓名、地址、电话号码和电子邮件。
电话簿的组织方式如下:
名字
地址
电话号码
电子邮件
名称 2
地址 2
电话号码 2
电子邮件 2
因此,您将能够预测哪一行包含哪些信息,并将其保存在结构的 vector 中。我的代码是这样的:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct Contact {
string name;
string address;
string phone;
string email;
};
string line;
vector<Contact> contacts;
int main(){
ifstream phonebook;
phonebook.open("phonebook.txt");
if (phonebook.is_open()){
int counter = 0;
int contactCounter = 0;
while( getline(phonebook,line) ){
//cout << "line is " << line;
if(line.length()<=0){
cout << "In the if";
}else{
if(counter % 4 == 0){
contacts[contactCounter].name = line;
cout << counter;
}else if(counter % 4 == 1){
contacts[contactCounter].address = line;
}else if(counter % 4 == 2){
contacts[contactCounter].phone = line;
}else if(counter % 4 == 3){
contacts[contactCounter].email = line;
contactCounter++;
}
}
counter++;
}
} else cout << "an error has occurred in opening the contact list";
cout << "Address of contacts[0]: " << contacts[0].address; //a test to see if it worked
return 0;
}
(我也有一个预制的文本文件来测试它) 但是每次我运行程序时它都会停止然后退出。任何信息?抱歉,我无法很好地解释我的思维过程。
最佳答案
您的 vector 在此处创建为空:vector<Contact> contacts;
.你需要 push_back
(或者 emplace_back
如果您不使用遗留 C++ 并且被允许更改您的类定义以包含用户定义的构造函数)它的每个新元素。
关于c++ - 如何读取文件并将每四行保存在结构变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124114/