如何在C ++中放置两个反斜杠 [英] How to put two backslash in 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 ++中放置两个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!