如何在C++中放置两个反斜杠 [英] How to put two backslash in C++

查看:35
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆