如何读取文件并将每四行保存在结构的变量中

How to read through a file and save every four lines in variables of a struct

本文关键字:四行 存在 保存 结构 变量 读取 何读取 文件      更新时间:2023-10-16

我对c++、编码和通用技术还很陌生,所以请耐心等待。

因此,最近在我的计算机科学课上,我被要求制作一个充当电话簿的程序,能够保存不同联系人的信息,如他们的姓名、地址、电话号码和电子邮件。

电话簿的组织方式如下:

名称

地址

电话号码

电子邮件

名称2

地址2

电话号码2

电子邮件2

因此,您可以预测哪一行包含哪些信息,并将其保存在结构的向量中。我的代码是这样的:

#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<Contact> contacts;。您需要push_back(或者emplace_back,如果您不在遗留C++上,并且可以更改类定义以包含用户定义的构造函数)中的每个新元素。