【问题标题】:Program always indents after printing char array?打印字符数组后程序总是缩进?
【发布时间】:2019-02-19 08:54:20
【问题描述】:

我的任务是编写一个可以在 bash shell 中使用的程序,该程序模仿某些默认的 Unix 命令,我们应该从头开始构建它们。这些命令之一是 PS1 命令,它应该将 $ 提示符更改为给出命令的任何参数。我已经在下面的代码中实现了这一点,它几乎可以完美地工作。

在使用 PS1 命令之前,提示符正常工作,它打印 $ 并且不缩进,而是让用户继续在同一行上键入。但是,使用该命令后,每当出现提示时,程序都会打印提示,然后换行。我需要它来打印 PS1 char* 而无需换行。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    int exit = 0;
    char* PS1 = "$";
    while(exit == 0){
        char* token;
        char* string;
        char input[500];
        printf("%s", PS1);
        fgets (input, 500, stdin);
        token = strtok(input, " ");
        if(strncmp(token, "exit", 4) == 0){
            exit = 1;
            break;
        }
        else if(strncmp(token, "echo", 4) == 0){
             token = strtok (NULL, " ");
             while (token != NULL){
                printf ("%s", token);
                printf("%s", " ");
                token = strtok (NULL, " ");
             }
        }
        else if(strcmp(token, "PS1") == 0){
            token = strtok (NULL, " ");
            char temp[300];
            strcpy(temp, &input[4]);
            PS1 = temp;        }
    }
} 

【问题讨论】:

  • fgets 读取的字符通常在末尾包含换行符。你可能想摆脱它。
  • fgets 在末尾保留换行符,以便打印。分配给分配后立即超出范围的临时数组是这里更大的问题。
  • 谢谢,n.m.,我可以通过temp[strlen(temp) - 1] = '\0';解决它

标签: c unix command-line strcpy


【解决方案1】:

fgets 在末尾保留换行符,以便打印。阅读该行后,您可以摆脱它:

fgets (input, sizeof(input), stdin);
strtok(input, "\n");

您的代码还有其他问题:

    ... else if (strcmp(token, "PS1") == 0) {
        token = strtok (NULL, " ");
        char temp[300];
        strcpy(temp, &input[4]);
        PS1 = temp;
    }

字符数组temp 是花括号中的块的局部,在关闭} 后将无效。这意味着PS1 是无效内存的句柄。那是未定义的行为。它现在可能不可见,但稍后当你添加更多命令时它会咬你。

如果字符在整个main 中可见,则将PS1 设为数组并复制到该数组可能会更好。 (数组可以初始化为在开头保存"$"。)

您还应该避免在&amp;input[4] 处使用显式索引。让strtok 的标记化处理这个问题。毕竟,可能会有额外的空白," PS1 Command: " 是有效的输入。

【讨论】:

    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多