mahnoor fatima
mahnoor fatima

Reputation: 41

How to pass character array in system() function in c++?

I want to execute linux commands using c++ platform and I am using system() but when i write:

cout<<"Enter the command"<<endl;
cin>>arraystring[size];

system(arraystring.c_str()); 

it gives error!

a4.cpp: In function ‘int main()’:
a4.cpp:75:20: error: request for member ‘c_str’ in ‘arraystring’, which is of non-class type ‘std::string [100] {aka std::basic_string<char> [100]}’
 system(arraystring.c_str());

What should i do to overcome this error?

Upvotes: 0

Views: 980

Answers (2)

shauryachats
shauryachats

Reputation: 10405

Actually, you have defined your arraystring variable as:

string arraystring[100];

Hence, when you write the statement

system(arraystring.c_str);

arraystring being an array of std::string, gives the error.

Change it to:

system(arraystring[size].c_str());

Upvotes: 2

R Sahu
R Sahu

Reputation: 206667

You can use:

std::string command;
std::cout << "Enter the command" << endl;
std::cin >> command;

system(command.c_str()); 

That will work as long as command is just one word. If you want to use multi-word commands, you can use:

std::getline(std::cin, command);
system(command.c_str()); 

Upvotes: 1

Related Questions