编译器没有对转义字符进行转义的解决方法

本文介绍了一种在C++中处理文件路径转义的方法,通过编写特定的字符串替换函数,解决了路径中斜杠字符引起的转义问题,确保程序能够正确识别并处理各种操作系统下的路径格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在编程中总会出现 将获取的路径作为参数传递到其他程序中,而获取的路径基本都是\,但是在识别过程中没有对他进行转义,所以会报错。下面就写一下针对路径进行\转义的代码。

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

//转义函数
int string_replase(string &s1, const string &s2, const string &s3)
{
	string::size_type pos = 0;
	string::size_type a = s2.size();
	string::size_type b = s3.size();
	while ((pos = s1.find(s2, pos)) != string::npos)
	{
		s1.replace(pos, a, s3);
		pos += b;
	}
	return 0;
}
int main() {
	//R"()"原样输出。不进行转义
    //string str(R"("C:\Users\Administrator\Desktop\test.txt")");//当然也可以直接写成这样,但这样就达不到我们测试的目的了
	//std::cout << "str==" << str << std::endl;
	string path =R"(\"C:\\Program Files\\AnsysEM\\HFSS15.0\\Win32\\hfss.exe\"  -ng   -batchsolve C:\\Users\\Administrator\\Desktop\\test\\connector.hfss)";
	//在这里就要先进行转义
	string_replase(path, "\\\\", "*"); string_replase(path, "\\", ""); string_replase(path, "*", "\\");
	std::cout << "path==" << path << std::endl;
return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值