我正在编写一个程序,我需要获取用户输入的程序名称和最多 2 个参数,然后执行该程序。我的问题是处理获取用户输入并将其连接到“./”字符串,因为程序将从给定目录执行。到目前为止,我尝试使用的是这个。
int main(int argc, char *argv[])){
int counter = 0;
char input[80];
char ProgramName[80];
printf("Enter program name and any parameters: ");
fgets(input, 80, stdin);
while(!isspace(input[counter])){
ProgramName[counter] = input[counter];
counter++;
}
}
我用isspace来检查空格,当我遇到它时,我知道后面跟着一个参数,那是程序名的结尾。我的问题是,如何将程序的名称连接到 ./而没有任何额外的尾随空白字符或任何不会导致它正确执行的内容?我尝试使用 strcpy 和 strcat,但是当我这样做时,我在命令窗口中得到了一堆奇怪的尾随字符。
最佳答案
您可能会看到尾随垃圾,因为 ProgramName
不是字符串:它缺少 NUL 终止符。你可以通过添加来解决这个问题
ProgramName[counter] = '\0';
在循环之后。
要在字符串前面添加 ./
,为什么不在开头添加呢?
int counter_a = 0, counter_b = 0;
...
ProgramName[counter_a++] = '.';
ProgramName[counter_a++] = '/';
while (!isspace(input[counter_b])) {
ProgramName[counter_a++] = input[counter_b++];
}
ProgramName[counter_a] = '\0';
最后,将 char
传递给 isspace
是错误的,因为 isspace
仅在非负输入上定义,但 char
可以是负数。您可以通过以下方式解决此问题:
while (input[counter] != '\0' && !isspace((unsigned char)input[counter])) {
我还在上面添加了对 '\0'
的检查。如果 input
不包含任何空格,则必须不要读取它的末尾。
关于将用户输入连接到 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113179/