【问题标题】:Getting input in system() function (Mac)在 system() 函数中获取输入 (Mac)
【发布时间】:2011-03-01 09:27:25
【问题描述】:
#include <iostream>
using namespace std;
int main() {
short int enterVal;
cout << "enter a number to say: " << endl;
cin >> enterVal;
system("say "%d"") << enterVal;
return 0;
}
是我目前正在尝试的。我希望用户输入一个数字,system() 函数基本上就是这样说的。上面的代码有一个错误,上面写着“'d' is not declared in this scope”。提前致谢。
【问题讨论】:
标签:
c++
macos
bash
system
【解决方案1】:
您必须手动格式化字符串。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
short int enterVal;
cin >> enterVal;
stringstream ss;
ss << "say \"" << enterval << "\"";
system(ss.str().c_str());
}
【解决方案2】:
你可以使用这样的东西:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
short int enterVal;
cout << "enter a number to say: " << endl;
cin >> enterVal;
ostringstream buff;
buff << "say " << enterVal;
system(buff.str().c_str());
return 0;
}
【解决方案3】:
您必须转义引号并格式化字符串。另一种方法是:
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
short int enterVal;
char command[128];
cout << "enter a number to say: " << endl;
cin >> enterVal;
snprintf((char *)&command, 128, "say \"%d\"", enterVal);
system(command);
return 0;
}
您还应该注意,您应该以编程方式避免使用 system() 调用,因为这会使您的程序容易受到安全漏洞的攻击。
如果您只是在胡闹并且不介意,那么请继续;)