CSP 201604-3 路径解析(文件模拟+stringstream流类对象)

题目描述

在这里插入图片描述在这里插入图片描述

题目分析

题目的意思是每次输入一个路径,可能是绝对的,也可能是相对的,要求我们判断它的种类并将他正则。一共有三种情况:

  1. 空串,返回当前路径(父路径)
  2. 第一个字符为不为‘/’,相对路径,加上当前路径后正则
  3. 第一个字符为为‘/’,绝对路径,直接正则

这道题思路想明白后很简单,但是实现需要一点功夫。通过这道题,我花时间整理了C和C++的流类对象及函数的用法,传送门:
【C 字符串处理】格式化输入输出
【C++】几种流类函数的使用

失分点

  1. 在使用getline(cin, op_path);之前,务必吞掉之前输入的回车!利用一行getchar();即可搞定;
  2. while (ss>>s)的用法是以空格为分隔符,使用前务必替换‘/’;
  3. 行尾不要多打出‘/’;
  4. 其他的注释写的非常详细,按需阅读即可。

代码

#define _CRT_SECURE_NO_WARNINGS
#define _ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)

#include <bits/stdc++.h>
//#include <iostream>
//#include<algorithm>

using namespace std;

int main()
{
	int P;//需要进行正规化操作的路径个数
	string cur_path;//当前目录
	cin >> P >> cur_path;

	getchar();//吞回车
	while (P--)
	{
		string op_path;//待操作路径
		getline(cin, op_path);//用getline可以读空格,即防止路径中出现空格
		if (op_path == "") op_path = cur_path;//若路径为空字符串,则正规化操作的结果是当前目录
		
		if (op_path[0] != '/')op_path = cur_path + '/' + op_path;//待处理的相对路径

		for (int i = 0; i < op_path.size(); i++)
		{
			if (op_path[i] == '/')op_path[i] = ' ';//替换为空格以便stringstream流操作
		}

		vector<string> segment_path;//用于存储输出路径段
		stringstream ss(op_path);
		string s;
		while (ss>>s)//名场面
		{
			if (s == ".")continue;
			else if (s == ".." && segment_path.empty())continue;
			else if (s == ".." && !segment_path.empty())segment_path.pop_back();
			else segment_path.push_back(s);
		}

		cout << '/';
		for (int i = 0; i < segment_path.size(); i++)
		{
			if (i == 0)cout << segment_path[i];
			else cout << '/' << segment_path[i];
		}
		cout << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值