Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define a macro that take the file's name and read, write to same name but different extensions using freopen()

Im trying to create some #define in c++, but now im stuck in this part

   #include<bits/stdc++.h>
#define FASTRW ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define IO(filename) freopen(filename + ".inp", "r", stdin); freopen(filename + "out", "w", stdout)


using namespace std;

int main(){
    FASTRW;
    IO("lmao");
    return 0;
}

the first define worked just fine, but my vs code showed the error message: "expression must have integral or unscoped enum type" to the IO("lmao").

i tried to use chat GPT and it said that the previous code, which was the
#define IO(filename) freopen(filename + ".inp", "r", stdin); freopen(filename + "out", "w", stdout)"
should be
#define IO(filename) freopen((filename + ".inp").c_str(), "r", stdin); freopen((filename + ".out").c_str(), "w", stdout)
because the string need to be converted to the c string type using c_str().
i expected this code should be able to read, write in 2 same filenames but different extensions: the .inp and .out.
But when i pasted, the error remained the same, i also used Bard, but the result was the same as the chat GPT one. Restart the vs code, the problem was still there. the message just disappears if i remove the string expressions and use directly the "filename".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you’re trying to do is concatenating strings, but there is no binary operator+ for char*.

You can either:

  • Wrap the filename in a std::string and "unwrap" with a call to .c_str (not so sure about the lifetime issues that will come with this one)
  • Limit the usability of your macro and restrict its input to string literals, in which case a single space will allow for concatenation (instead of a +)

For the first solution:

#define IO(filename) freopen((std::string{filename} + ".inp").c_str(), "r", stdin); freopen((std::string{filename} + "out").c_str(), "w", stdout)

For the second solution:

#define IO(filename) freopen(filename ".inp", "r", stdin); freopen(filename "out", "w", stdout)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading