gpt4 book ai didi

c - 如何在没有垃圾的情况下从 C 命令行中获取带空格的参数

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:17 25 4
gpt4 key购买 nike

我正在尝试获取命令行参数以在 exec 中使用它但我的代码无法正常工作,因为它返回垃圾作为输出。(我是 ubuntu 用户)
这是我到目前为止所做的:

    #include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc,char *argv[]){

char command[1024];
int i;
fflush(stdin); // i try to empty the buffer

for ( i = 1; i < argc; ++i) {
strcat(command, argv[i]);
strcat(command," ") ; //here i try to copy the arguments
}
printf("%s\n",command);

return 0;
}

编译后在终端的输出是:

ubuntu-gnome@ubuntu-gnome:~/Desktop$ ./1 theo psallidas
����*theo psallidas

最佳答案

你需要一个以 NUL 结尾的字符串来使用 srtcat:

The strcat() function shall append a copy of the string pointed to by s2 (including the terminating null byte) to the end of the string pointed to by s1. The initial byte of s2 overwrites the null byte at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.

char command[1024];

应该是

char command[1024] = "";

fflush(stdin); 是未定义的行为(但你根本不需要这一行)。

关于c - 如何在没有垃圾的情况下从 C 命令行中获取带空格的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com