C++|通过fstream读写TXT文件字符串切割

参考:
全网最详细C/C++文件读写总结
https://blog.csdn.net/m0_48643365/article/details/123512860
C/C++文件读写(最全方法,多种实现)
https://blog.csdn.net/weixin_50964512/article/details/123240393
C+±string常用函数整理(建议收藏)
https://blog.csdn.net/zhaitianbao/article/details/118993685

位置从0开始
在这里插入图片描述

// CPlusReadWriteFile.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <fstream>
#include <vector>
#include <memory>
#include <iostream>

// 写文件
void writeTxt() {
	const unsigned int RowCount = 2;
	std::string paraInit[RowCount][2] = { { "QTree","Test" },{ "Rob","Sleep" } };
	std::ofstream of;
	of.open("Test.txt", std::ios::out | std::ios::trunc);
	unsigned int i = 0;
	for (int i = 0; i < RowCount; i++)
	{
		char paraTemp[128] = { 0 };
		// 添加空行
		//sprintf_s(paraTemp, "[Name]%-32s[Doing]%-32s\n", paraInit[i][0].c_str(), paraInit[i][1].c_str());
		// 未添加空行
		sprintf_s(paraTemp, "[Name]%-s[Doing]%-s\n", paraInit[i][0].c_str(), paraInit[i][1].c_str());
		of.write(paraTemp, strlen(paraTemp));
	}
	of.close();
}

// 去掉空格
void Trim(std::string &str)
{
	if (str.empty())
	{
		return;
	}
	str.erase(0, str.find_first_not_of(" "));
	str.erase(str.find_last_not_of(" ") + 1);
	return;
}

struct  MyList
{
	std::string name;
	std::string doing;
public:
	MyList(std::string Name, std::string Doing) :name(Name), doing(Doing) {}
};
std::vector<std::shared_ptr<MyList>> m_List;

// 读文件
void ReadTxt() {
	std::ifstream fin;
	std::string str = "";
	fin.open("Test.txt", std::ios::in);
	// 如果打开文件失败创建文件
	if (!fin.is_open())
	{
		writeTxt();
		fin.open("Test.txt", std::ios::in);
	}
	// 每行读取
	while (getline(fin, str))
	{
		// 找到该字符串位置
		auto posName = str.find("[Name]");
		auto posDoing = str.find("[Doing]");
		//auto Name = str.substr(posVendor + sizeof("[Name]") - 1, posModel - posVendor - sizeof("[Name]"));
		/*
		1.s=ss.substr(1,3); // 提取函数,提取ss字符串从1位置起的3个字符给s字符串
		2.s=ss.substr(); // 提取函数,提取ss字符串的所有内容给s字符串
		3.s=ss.substr(3); // 提取函数,提取ss字符串从3位置起的所有内容给s字符串
		*/
		auto Name = str.substr(posName + sizeof("[Name]") - 1, posDoing - posName - sizeof("[Name]")+1);
		Trim(Name);
		auto Doing = str.substr(posDoing + sizeof("[Doing]") - 1);
		Trim(Doing);
		std::shared_ptr<MyList> MyListNode = std::make_shared<MyList>(Name, Doing);
		m_List.push_back(MyListNode);
	}
}

int main()
{
	ReadTxt();
	std::cout <<"Name:"<< m_List.at(0)->name <<"		"<< "Doing:"<<m_List.at(0)->doing
		<<std::endl<<"Name:"<< m_List.at(1)->name << "		" <<"Doing:"<<m_List.at(1)->doing<<std::endl;
	system("pause");

    return 0;
}



在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

奇树谦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值