C++实现分割读取txt文件以及对齐打印设置

       假设现在有txt文件如下,需要将里面每一项的内容分别读取并存储,以读取文件中的FrameNo、Y_bits以及Y_psnr三个变量为例进行分析。

      txt文件下载:点击下载txt文件


完整C++程序如下:

        txt_read.cpp

#include<iostream>
#include<iomanip>
using namespace std;

void errorMsg(const char *msg) {
	printf("error:%s\n", msg);
#ifdef _WIN32
	system("pause");
#endif
	exit(-1);
}

void read_one_frame_info(int frameNo, int *y_bits, double *y_psnr, char *fileName) {
	int frameno = 0, qp = 0, uv_bits = 0;
	char temp[50];
	char errorText[50];
	FILE *fp;

	fp = fopen(fileName, "r"); 
	if (fp == NULL) {
		sprintf(errorText, "File %s not found", fileName);
		errorMsg(errorText);
	}

	while (!feof(fp))
	{
		fscanf(fp, "%s", temp);
		if (strcmp(temp, "FrameNo:") == 0)
		{
			fscanf(fp, "%s", temp); // get frame number
			frameno = atoi(temp);

			if (frameno == frameNo)
			{
				break;
			}
		}
	}

	if (feof(fp))
	{
		sprintf(errorText, "In function read_one_frame_info: frame number %d not found", frameNo);
		errorMsg(errorText);
	}


	fscanf(fp, "%s", temp);
	fscanf(fp, "%s", temp); // get Y_bits
	*y_bits = atoi(temp);

	fscanf(fp, "%s", temp);
	fscanf(fp, "%s", temp); // get UV_bits

	fscanf(fp, "%s", temp);
	fscanf(fp, "%s", temp); // get QP

	fscanf(fp, "%s", temp);
	fscanf(fp, "%s", temp); // get Y_psnr
	*y_psnr = (float)atof(temp);

	fclose(fp);
}

void main()
{
	int frameNum = 100;
	int *y_bit;
	double *y_psnr;
	y_bit = (int *)malloc(sizeof(int)*frameNum);
	y_psnr = (double *)malloc(sizeof(double)*frameNum);
	char *fileName = "per_frame_stat.txt";
	for (int i = 0; i < frameNum; i++) {
		read_one_frame_info(i, &y_bit[i], &y_psnr[i], fileName);
		//普通输出
		//cout << "FrameNo:" << i << "  " <<
			//"bitRate:" << y_bit[i] << " " << " PSNR:" << y_psnr[i] << endl;
		//对齐输出
	    cout <<"FrameNo:"<< setw(10) << setfill(' ') << left <<i <<"  "<<
			"bitRate:" << setw(10) << setfill(' ') << left<<y_bit[i] << " " << " PSNR:" <<y_psnr[i] << endl;
	}
}
 注意:

cout设置对齐方式:..........<< setw(10) << setfill(' ') << left.......... 

        对齐与非对齐方式运行结果如下,当然不同的宽度间隔可以灵活调整,也可以指定读取txt文件中的其它内容。

非对齐:


对齐:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

rs勿忘初心

您的鼓励将是我的最大创动原动力

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

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

打赏作者

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

抵扣说明:

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

余额充值