c++读txt文本,并按键值key-value取值

在这里插入图片描述


```c
#include <iostream>
#include <fstream> 
#include <string>
using namespace std;
int GetValue(std::string strSource, std::string strkey)
{
	if (strSource.empty())
	{
		return 0;
	}
	int npos = strSource.find(strkey);
	int npos2 = strSource.find(" ", npos+ strkey.size());
	string strx = strSource.substr(npos + strkey.size(), npos2 - npos - strkey.size());
	return atoi(strx.c_str());
}

void main()
{
	std::fstream readfile("2.txt");
	char buf[512] = { 0 };
	while (readfile.getline(buf, 512))
	{
		if (buf[0] == '\\' || buf[0] == '#'||buf[0] == '//')
		{
			continue;
		}
		cout << buf << endl;

		std::string str = buf;

		cout << GetValue(str, "x=")<<" " << GetValue(str, "y=") << " " << GetValue(str, "size=") << " " << GetValue(str, "type=") << endl;

	}
	readfile.close();

	/*
	#x:坐标 y:坐标 size:缺陷大小 type:缺陷类型(图标类型)
	x=13  y=109  size=12   type=7
	x=11  y=119  size=2   type=1
	*/


	system("pause");
}

结果:
在这里插入图片描述
但是推介下面这种方式读取文件

void main()
{
	//#include <fstream> 
	std::fstream readfile("1.txt");
	string strOut;
	while (getline(readfile, strOut))
	{
		if (strOut[0] == '\\' || strOut[0] == '#' || strOut[0] == '//')
		{
			continue;
		}
		cout << strOut.c_str() << endl;
		cout << GetValue(strOut, "x=") << " " << GetValue(strOut, "y=") << " " << GetValue(strOut, "size=") << " " << GetValue(strOut, "type=") << endl;

	}

	readfile.close();
	system("pause");
	}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发如雪-ty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值