LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   system(variable) is it possible?? (https://www.linuxquestions.org/questions/programming-9/system-variable-is-it-possible-542324/)

sudif 04-01-2007 05:57 AM

system(variable) is it possible??
 
i want to make a c++ program that do something like this
string str;
cin >> str;
str="cat " + str;
int rv=system(str);

is there a way to do it?

graemef 04-01-2007 06:14 AM

It should be fine, the only thing to watch out for is that you will probably need to convert the string to a character array check out the method c_str().

ta0kira 04-01-2007 10:40 AM

Also if the first arg in string addition is a string const you will need explicit construction:
Code:

string str;
cin >> str;
str=string("cat ") + str;
int rv=system(str.c_str());

The >> operator will only give you a section of non-whitespace, so I'd use getline instead in case someone wants to arrive at the filename with ``, or it has spaces and requires "". That involves resizing the string in advance, though:
Code:

str.resize(512);
cin.getline(&str[0], 512);

--or--
Code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  char input[512];
  cin.getline(input, 512);
  string command = string("cat ") + input;
  return system(command.c_str());
}

Save that as 'test.cpp', and after compiling run it 3 times using each of these as input:
Code:

test.cpp
`ls test.cpp`
"test.cpp"

ta0kira


All times are GMT -5. The time now is 06:15 PM.