如何在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;
}
相关文章