c++ - 如何在 C++ 中通过 system() 函数使用字符串变量

标签 c++

<分区>

最近我开发了一个程序,我必须在其中调用 system();,它接受一个 const char*。我需要在此调用中使用一个字符串数组。这是一些示例代码。

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main()
{
    string stackoverflow[5] = {"a", "b", "c", "d", "e"};
    int i = 0;

    while(i <= 5)
    {
        system("wget -O" + stackoverflow[i] + "\"www.google.com\"");
        i++;
    }   
}

旁注:我尝试使用 const char b = stackoverflow[i].c_str() 但出现错误:

expression must have integral or unscoped enum type

'+' cannot add two pointers

顺便说一句,我正在使用 Visual Studio。我不知道此时我应该做什么。

感谢阅读。我是新手,所以任何帮助将不胜感激。我希望有一个不需要将我的数组转换为 vector 的解决方案,因为我在这个项目中有很多代码,这将需要重组大量代码。 PS 抱歉我在 c+p 失败了缩进

最佳答案

先创建一个组合字符串,然后使用std::string.c_str()函数。

std::string combined = "wget -O" + stackoverflow[i] + "\"www.google.com\"";
system(combined.c_str());

关于c++ - 如何在 C++ 中通过 system() 函数使用字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50282624/

相关文章:

c++ - omp_get_max_threads() 在并行区域返回 1,但它应该是 8

C++11 相当于 python 的 x, y, z = array

c++ - 使用双击事件创建 QLabel 时出现链接器错误

c++ - 在此函数中通过引用传递参数

c++ - Boost Geometry/intersection() 似乎返回不一致的结果

使用 Visual Studio 的 C++ 编译错误(LNK1120 和 LNK2019)

c++ - 如何防止声明为局部变量的对象在堆栈中分配?

c++ - 构造函数中的 "my_constructor : variable(x)"和 "this.variable = x"有区别吗?

c++ - while 内打印增量计数变量值

c++ - 关于 C++ 中的二维数组初始化