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

标签 c++

我在 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/

相关文章:

c++ - 具有不同构造函数参数的 CPP 对象数组

c++ - 替换 SHDOLCC.DLL 文件以自定义 Web 浏览器的上下文菜单

c++ - 显式转换运算符和常量引用限定

c++ - 如何分配线程本地存储?

c++ - ID3D11Buffer 中可以存储的最大数据量是多少?

c++ - 如何终止 cin>> 输入特定的单词/字母/数字/等

c++ - 谁能帮我把这个结构翻译成delphi记录?

c++ - 如何在 Linux unsing QProcess 下执行 shell 命令?

c++ - 在 C++ 中填充 C 结构的填充字节? (不涉及结构包装!)

c++ - OpenGL 中的绘制顺序