如何将参数从c++程序传递给cmd

How to pass an argument from a c++ program to cmd?

本文关键字:cmd 程序 c++ 参数      更新时间:2023-10-16

我正在尝试使用用户的输入作为将传递给cmd的参数。。。

我知道要从我的程序中使用cmd,我需要使用这个:

system("SayStatic.exe hello world");

但这正是我需要的:

char item[100];
gets(item);
//after getting the input I need to pass it to SayStatic.exe that is the part I dont know

我知道我不能使用sysytem();为此,但其他类似spawnl()或execl()的方法会奏效吗?

首先,不要使用gets()。它不应该包含在标准库中,因为比字符串长的输入将覆盖堆栈内存并导致未定义的行为(可能是某种崩溃)。如果您使用的是C字符串,fgets()是一个可以接受的替代品。

你可以使用这样的C++字符串:

std::string line;
std::getline(std::cin, line);
system(("SayStatic.exe " + line).c_str());