Question

Let me begin by saying that I could not find an identical question, but my search keywords were fairly generic, and so if you know of a thread that answers my question, point it out to me and I'll close this thread.

I'm re-writing a bash script of mine in c++ to help me get a firmer grasp on the language. The problem I'm running into is as follows:

string input = "/wam/wxx.cpp";
string output = "/wam/wxx.exe"; 
system ("/MinGW/bin/g++.exe input  -o output");

(This is just a small illustration; in my actual code the variables are user-input)

Obviously I am passing the words 'input' and 'output' to my compiler instead of the variables of those names. I have tried

system ("/MinGW/bin/g++.exe" input  "-o" output);

as well as other combinations of quoting/not quoting, none of which work either. The system command wants quotation marks, so is there a way to have my variables properly recognized in those quotes? (Currently I am saving these variables to a text file, then loading them into a bash script that runs the compiler, which defeats the purpose of me writing this in c++ to begin with.)

Thanks in advance!

EDIT: To clarify, I am

using namespace std 
Was it helpful?

Solution

Since they are (presumably) std::string, you can just paste them together with +, like this:

std::string cmd = "/MinGW/bin/g++.exe";

std::string fullcmd = cmd + " " + input + " -o " + output;
system(fullcmd.c_str());

You need fullcmd.c_str() since system takes a C style string, not a C++ style string.

OTHER TIPS

This should help:

string input = "/wam/wxx.cpp";
string output = "/wam/wxx.exe"; 
string command = "/MingW/bin/g++.exe "
command += input;
command += " -o "
command += output;
system(command.c_str());

You need std::string::c_str() to convert strings to char arrays, and you can't add an std::string to a string literal, however, you can add a literal to a std::string, or an std::string to an std::string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top