我试图制作一个可以通过在 shell 中运行命令来打开网站的程序。但我收到此错误:“不存在从“std::__1::string”到“const char *”的合适转换函数”。但奇怪的是它仍然按照我想要的方式运行,我只是不明白为什么?
代码:
#include <iostream>
int main() {
std::string website;
std::cout << "what website would you like to open?" << "\n";
std::cin >> website;
if (website.find("https://") != std::string::npos) {
// Website contains "https"
}
else if (website.find("http://") != std::string::npos) {
// Website contains "http"
}
else {
website = "https://" + website;
}
std::string command = "open " + website;
int returnCode = system(command);
if (returnCode != 0) {
// Handle error if needed
std::cout << "Error executing command" << "\n";
}
return 0;
}
我尝试将命令函数设为常量,但似乎没有成功。
您应该通过 std::string
方法访问
access
c_str()
的空终止字符数组。
int returnCode = system(command.c_str());
您所做的是未定义的行为(即使它恰好在这种情况下起作用)。