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?

3
  • Can you print the output of std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs"); Commented Oct 30, 2020 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. Commented Oct 30, 2020 at 14:36
  • FYI: Don't use using namespace std;: stackoverflow.com/questions/1452721/…. Commented Oct 30, 2020 at 15:00

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.