【问题标题】:Concat user input onto a str in C将用户输入连接到 C 中的字符串中
【发布时间】:2015-10-13 21:44:38
【问题描述】:

我正在编写一个程序,我需要获取用户输入的程序名称和最多 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,但是当我这样做时,我在命令窗口中得到了一堆奇怪的尾随字符。

【问题讨论】:

  • fscanf 似乎适合 C
  • scanf 永远不合适。
  • 您希望在上述程序中的什么时候添加./?事实上,该字符串不会出现在您显示的代码中任何地方。否则,它看起来并没有完全错误。
  • 另请注意,您实际上不必为此进行复制。您可以在缓冲区的开头将两个字符留空,读取输入,将'/' 放在第一个非空白字符之前,将'.' 放在前面。然后用'\0' 替换空格,同时记录指向非空白序列开头的指针。
  • 引导性问题:如果用户输入的字符串没有空格会怎样? while 循环会终止吗?

标签: c char concat


【解决方案1】:

您可能会看到尾随垃圾,因为 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 不包含任何空格,则必须这样做才能读取到它的末尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多