How to put two backslash in C++

前端 未结 5 1541
北海茫月
北海茫月 2021-01-15 19:48

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

5条回答
  •  终归单人心
    2021-01-15 20:08

    In this line:

    if(newpath[i] = '\\')
    

    replace = with ==.

    In this line:

    newpath[i] +=  '\\';
    

    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.

    Try this instead:

     #include 
     #include 
     #include 
    
    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;
    }
    

提交回复
热议问题