C++ 系统命令最后输出 0
C++ System command outputs 0 at end
所以我正在编写一个 C++ 程序,运行是程序中的一个命令。但是,每当我执行 运行 命令时,它都会在应该输出的任何内容末尾输出 0。示例:
The random int I was thinking of was 130
本来应该输出The random int I was thinking of was 13
但最后还是输出了0。这是我对 运行 命令的代码:
printf("Running file: %s\n", fileName);
if(!exists(fileName))
{
printf("That file does not exist.\n");
return;
}
char buffer [7+strlen(fileName)];
int n;
n = sprintf(buffer, "php -f %s", fileName);
cout << system(buffer) << endl;
我认为它与 php
命令没有任何关系,因为每当我在我的终端中输入时,php -f <filenamehere>
它都会输出 The random int I was thinking of was 13
。我想不出别的了。
system
函数returns"result"的执行,其中0表示成功,其他值表示各种类型的失败(包括可执行文件本身的结果,如果适用的)。
您正在使用 cout
打印该值,这就是它打印 0
的原因 - 这就是它打印 0
的原因。
你可能想做这样的事情:
int result = system(...);
if (result != 0)
{
cout << "system returned " << result << " which means it failed..." << endl;
}
请注意,无论您使用 system
运行 的什么输出都将转到 stdout
,它不会返回到应用程序本身,它只是打印到控制台 [或stdout
要去哪里。
系统命令return只有执行状态。
要捕获并打印输出,请参阅此 link
中的选项
How to execute a command and get output of command within C++ using POSIX?
所以我正在编写一个 C++ 程序,运行是程序中的一个命令。但是,每当我执行 运行 命令时,它都会在应该输出的任何内容末尾输出 0。示例:
The random int I was thinking of was 130
本来应该输出The random int I was thinking of was 13
但最后还是输出了0。这是我对 运行 命令的代码:
printf("Running file: %s\n", fileName);
if(!exists(fileName))
{
printf("That file does not exist.\n");
return;
}
char buffer [7+strlen(fileName)];
int n;
n = sprintf(buffer, "php -f %s", fileName);
cout << system(buffer) << endl;
我认为它与 php
命令没有任何关系,因为每当我在我的终端中输入时,php -f <filenamehere>
它都会输出 The random int I was thinking of was 13
。我想不出别的了。
system
函数returns"result"的执行,其中0表示成功,其他值表示各种类型的失败(包括可执行文件本身的结果,如果适用的)。
您正在使用 cout
打印该值,这就是它打印 0
的原因 - 这就是它打印 0
的原因。
你可能想做这样的事情:
int result = system(...);
if (result != 0)
{
cout << "system returned " << result << " which means it failed..." << endl;
}
请注意,无论您使用 system
运行 的什么输出都将转到 stdout
,它不会返回到应用程序本身,它只是打印到控制台 [或stdout
要去哪里。
系统命令return只有执行状态。
要捕获并打印输出,请参阅此 link
中的选项How to execute a command and get output of command within C++ using POSIX?