【c++基础】ifstream、istringstream的示例应用

该代码示例展示了如何利用C++的ifstream和istringstream从phonebook.txt文件中读取姓名和电话号码,将数据存储到vector<PersonInfo>结构体中,每个结构体包含姓名和电话号码列表。
摘要由CSDN通过智能技术生成

本次示例所使用文件为phonebook.txt文件,该文件记录了一些人的名字以及电话,文件格式如下(每一行为一条记录,以人名开始,后面跟随一个或多个电话):

james 15523951231 13212304212
jardon 14240324832
kebo 13424596304 15321340234 14920471921

 任务需求:同时使用ifstream、istringstream将phonebook.txt中每条记录都读取到vector<struct>中,struct包含人名信息与电话信息。

代码示例如下:

.h文件:

#pragma once

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

struct PersonInfo
{
	string name;
	vector<string> phone;
};

vector<PersonInfo> getfileline(const string& txtstr);

.cpp文件:

# include "function.h"

vector<PersonInfo> getfileline(const string& txtstr) {
	ifstream infile(txtstr, ifstream::in);
	vector<PersonInfo> people;
	if (infile.is_open())
	{
		string line;
		int linenums = 0;
		while (getline(infile, line)) {
			cout << "line:" << line << endl;
			++linenums;

			PersonInfo info;
			string phonewords;
			istringstream instring(line);
			instring >> info.name;
			while (instring >> phonewords) {
				info.phone.push_back(phonewords);
				cout << "linenums:" << linenums << " name: " << info.name << " phone: " << info.phone.back() << "" << endl;
			}
			people.push_back(info);
		}
		infile.close();
	}
	else
		cerr << "input of file is error!" << endl;
	return people;
}

mian.cpp文件:

#include "function.h"

int main() {

	getfileline("iotest.txt");

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卖报的大地主

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值