如何在c++中的system()函数中传递字符数组

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

本文关键字:函数 数组 字符 c++ 中的 system      更新时间:2023-10-16

我想使用c++平台执行linux命令,我使用的是system(),但当我编写时:

cout<<"Enter the command"<<endl;
cin>>arraystring[size];
system(arraystring.c_str()); 

它会出错!

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());

我该怎么做才能克服这个错误?

实际上,您已经将arraystring变量定义为:

string arraystring[100];

因此,当您编写语句时

system(arraystring.c_str);

作为std::string的阵列的arraystring给出了误差。

更改为:

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

您可以使用:

std::string command;
std::cout << "Enter the command" << endl;
std::cin >> command;
system(command.c_str()); 

只要command只是一个单词,它就会起作用。如果你想使用多字命令,你可以使用:

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