We have a large amount of “demo” code that uses sprintf and cstrings to construct filenames. I’d like to replace it with c++ strings to allow very long filenames and because it gives a cleaner syntax.
So essentially we need to convert blocks like
ofstream some_file;
char filename[100];
sprintf(filename,"%s/soln%i.dat",a.c_str(), b);
some_file.open(filename);
into something like
ofstream some_file((a + "soln" + to_string(b) + ".dat").c_str());
However because this is used in a lot of places I’d like to use some kind of automatic conversion (i.e. sed expressions, emacs function/macros, visual studio?, etc.). The difficulties (that I can see) are:
-
The contents of the sprintf statement can be anything. (So we need to parse an sprintf statement?)
-
some_file and filename could be declared anywhere, could be named anything and often are reused for output to multiple files. (So we need to parse C++?)
Is this possible/feasible?
For bonus points can we avoid having to call .c_str() on the string (without changing the ofstream constructor)?
Here’s something simpler, w/o Yassnippet:
You could bind it to any key you like and use like so:
sprintfyou want to replace, for example by doing M-%sprintf, then call this function. It will prompt you to give it the name of the file where you want to print the message (probably I could make it more complex, and search upwards for the place where ofstream was declared, but if you say it may have been declared in an arbitrary place, that sounds like a wasted effort).given your original example. Obviously, if you think that adding a
to_string()around arguments is more likely to be the case, then it is easy to do, given some more effort it will be also easy to avoid concatenating empty strings too, but some times it may change the effect / interpretation of the+operator, so I decided to keep it like this. I’ll try to make it into a yassnippet script a bit later today, so that it would be possible to jump to uncertain places in the replaced string interactively and have some pre-defined replacements too.