2015-10-13 57 views
0

我正在编写一个程序,我需要获得用户输入的程序名和最多2个参数,然后执行所述程序。我的问题是处理用户输入并将其与一个“./”字符串连接起来,因为程序将从给定目录执行。到目前为止我尝试过的是这样的。Concat用户输入到一个str中的C

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,但是当我这样做时,我在命令窗口中遇到了一堆奇怪的结尾字符。

+0

fscanf似乎适用于C – sehe

+1

'scanf'永远不适合。 – melpomene

+0

在上面的程序中,你希望添加'。/'?事实上,该字符串不会出现在您显示的代码中的任何位置。否则,它看起来不完全错误。 – 5gon12eder

回答

2

您可能会看到尾随垃圾,因为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'; 

最后,传递到charisspace错误的,因为isspace仅在非负输入来定义,但char可以是负的。您可以修复使用:

while (input[counter] != '\0' && !isspace((unsigned char)input[counter])) { 

我还添加了检查上面'\0'。如果input不包含任何空格,则这是必要的,以避免超出input的末尾。