如何读取文件并将每四行保存在结构的变量中
How to read through a file and save every four lines in variables of a struct
我对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++上,并且可以更改类定义以包含用户定义的构造函数)中的每个新元素。
相关文章:
- 向量是否存在行主要形式?
- 如果存在 QSQLITE 数据库,则根据 qt 中的行值插入或更新
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 如何读取文本文件的第二、第三和第四行.C++
- 检查数组行中每行C++是否始终存在相同的值
- 我想将四个字节合并为一个数字以进行串行传输
- 句子转换器在存在新行的情况下不起作用
- 如何解决错误 C2719 在 Visual Studio 2010 C++ 中不存在代码行时
- 当存在新的串行端口时信号
- 为什么 sqlite 的删除总是成功,即使要删除的行不存在?
- VP 矩阵的第四行
- 如何读取文件并将每四行保存在结构的变量中
- 有效的算法来检查是否存在具有相同值的行和列
- 确定是否存在串行端口,Linux C/C++
- 如何在预先存在的3个标准压缩行/列数组上包装Eigen::SparseMatrix
- 避免基于模板运算符的存在编译某些行
- 是否存在串行化boost::signals2信号调用的现有方法
- 读取Txt文件,逐行,在两个列表中存储多个类型,如果存在的话
- g++ openCV 编译错误在不存在的行上
- QtableWidget中的主键-如果行存在,则更新,否则添加