1

I'm a newbie with C++. I'm trying to learn string replacement.

I'm writing a short (supposed to be a tutorial) program to change directory names.

For example, I want to change "/home" at the beginning of a directory name with "/illumina/runs" thus:

#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

#include<iostream>
#include <string>
#include <regex>
#include <iterator>
using namespace std;

std::string get_current_dir() {
   char buff[FILENAME_MAX]; //create string buffer to hold path
   GetCurrentDir( buff, FILENAME_MAX );
   string current_working_dir(buff);
   return current_working_dir;
}

int main() {
   string b2_dir = get_current_dir();
   std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");
   cout << b2_dir << endl;
   return 0;
}

I'm following an example from http://www.cplusplus.com/reference/regex/regex_replace/ but I don't see why this isn't changing.

In case what I've written doesn't make sense, the Perl equivalent is $dir =~ s/^\/home/\/illumina\/runs/ if that helps to understand the problem better

Why isn't this code altering the string as I tell it to? How can I get C++ to alter the string?

con
  • 5,767
  • 8
  • 33
  • 62
  • Can you print the output of `std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");` – Harry Oct 30 '20 at 14:30
  • FYI: if you're `using namespace std;`, you can drop all of the `std::`'s in your code: so `std::string get_current_dir()` becomes `string get_current_dir()` and `std::regex` just becomes `regex`. – flipjacob Oct 30 '20 at 14:36
  • FYI: Don't use `using namespace std;`: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – AVH Oct 30 '20 at 15:00

1 Answers1

6

std::regex_replace does not modify its input argument. It produces a new std::string as a return value. See e.g. here: https://en.cppreference.com/w/cpp/regex/regex_replace (your call uses overload number 4).

This should fix your problem:

b2_dir = std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");
AVH
  • 11,349
  • 4
  • 34
  • 43