How to put two backslash in C++(如何在C++中放置两个反斜杠)
问题描述
我需要创建一个接受目录路径的函数.但是为了让编译器读取反斜杠,我需要创建一个函数,将一个反斜杠变成 2 个反斜杠..到目前为止这是我的代码:
i need to create a function that will accept a directory path. But in order for the compiler to read backslash in i need to create a function that will make a one backslash into 2 backslash.. so far this are my codes:
string stripPath(string path)
{
char newpath[99999];
//char *pathlong;
char temp;
strcpy_s(newpath, path.c_str());
//pathlong = newpath;
int arrlength = sizeof(newpath);
for (int i = 0; i <= arrlength ;i++)
{
if(newpath[i] == '\')
{
newpath[i] += '\';
i++;
}
}
path = newpath;
return path;
}
此代码接收来自用户的输入,该输入是带有单个反斜杠的目录路径.问题是它给出了一个脏文本输出;
this code receives an input from a user which is a directory path with single backslash. the problem is it gives a dirty text output;
推荐答案
在这一行:
if(newpath[i] = '\')
将 =
替换为 ==
.
在这一行:
newpath[i] += '\';
这应该是将 添加到字符串中(我认为这就是您想要的),但它实际上对当前字符进行了一些时髦的
char
数学运算.因此,您不是插入字符,而是破坏了数据.
This is supposed to add a into the string (I think that's what you want), but it actually does some funky
char
math on the current character. So instead of inserting a character, you are corrupting the data.
试试这个:
#include <iostream>
#include <string>
#include <sstream>
int main(int argc, char ** argv) {
std::string a("hello\ world");
std::stringstream ss;
for (int i = 0; i < a.length(); ++i) {
if (a[i] == '\') {
ss << "\\";
}
else {
ss << a[i];
}
}
std::cout << ss.str() << std::endl;
return 0;
}
这篇关于如何在C++中放置两个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在C++中放置两个反斜杠


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01