程序在打印char数组后总是缩进?

问题描述 投票:0回答:1

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

在使用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;        }
    }
} 
c unix command-line strcpy
1个回答
0
投票

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是无效内存的句柄。这是未定义的bevaiour。它现在可能不可见,但是当你添加更多命令时它会在以后咬你。

如果在整个PS1中可见的字符并复制到那个字符,那么使main成为一个数组可能会更好。 (可以初始化数组以在开头保存"$"。)

您还应该避免使用qazxsw poi中的显式索引。让qazxsw poi进行标记化处理。毕竟,可能有额外的空白区域,&input[4]是有效的输入。

© www.soinside.com 2019 - 2024. All rights reserved.