C:如何在不输入ENTER(\ n)的情况下获取用户输入?

时间:2016-02-05 20:41:43

标签: c user-input fgets

我正在尝试读取一个用户输入字符串,该字符串仅记录用户输入键而不用' \ n'。

因此,分隔用户输入的命令和参数,例如" mkdir你好" (" mkdir" =命令," hello" =参数)返回参数(" hello \ n")。

有没有办法删除' \ n'有效?

另外,你如何null终止字符串?

int main(void) {

    char directoryName[129] = "";

    printf("\nProgram Start... \n\n");

    // getting user input string
    // and splitting command and argument
    char inputString[129];
    char delimiter[] = " ";
    char *line;
    char *arg;
    struct tree_node *root = make_tree_node("root\0");
    //struct tree_node *cwd = make_tree_node("root\0");
    struct tree_node *cwd = root;

    printf("/%s >", directoryName);

    while (fgets(inputString, 128, stdin)) {

        // char * before strsep, set pointer to be original checkString
        // original checkString
        // then free memory 

        // gets argument and stores as arg
        line = malloc(sizeof(char) * strlen(inputString));
        strcpy(line, inputString);
        arg = strsep(&line, delimiter);
        arg = strsep(&line, delimiter);
        printf("your argument: %s\n", arg);

        printf("/%s >", directoryName);
}

整个代码:

#include <stdio.h> /* For fgets(), fprintf() and printf() */
#include <stdlib.h> /* For EXIT_FAILURE */
#include <ctype.h> /* For isspace() */
#include <string.h>
#include <stddef.h>

// COMMANDS
char exitProgram[] = "exit";
char listDirectory[] = "ls";
char commandDirectory[] = "cd";
char makeDirectory[] = "mkdir";
char removeDirectory[] = "rmdir";

// holds a string buffer of length 128
// a pointer to its parent
// a pointer to the first node of the list of children
typedef struct tree_node {
    char string_buffer[128];
    struct tree_node *parent;
    struct list_node *first_child; // first node of list of children?
} tree_node;

// pointer to tree node
// pointer to next item in the list
typedef struct list_node {
    struct tree_node *tree;
    struct list_node *next;
} list_node;

// allocates the right amount of space for a tree node
// sets the pointers to NULL
// initialises the string buffer with the given name
// returns a pointer to the tree node
struct tree_node *make_tree_node(char *name) {
    tree_node *tree = malloc(sizeof(*tree));
    tree -> parent = NULL;
    tree -> first_child = NULL;
    strcpy(tree -> string_buffer, name);
    return tree;
}

// allocates a new list node
// assigns the fields for the tree node it references and the next list node
// returns a pointer to the new list node
struct list_node *make_list_node(struct tree_node *v, struct list_node *next) {
    list_node *instance = malloc(sizeof(*instance));
    instance -> tree = v;
    instance -> next = next;
    return instance;
}

 // checks whether directory named arg already exists in current working directory
 // creates the directory if it does not exist
 // if arg is NULL, the function should print an error message
void do_mkdir(struct tree_node *cwd, char *arg) {

    printf("Making Directory with name %s \n", arg);

    // check if directory exists
    struct list_node *subDir = cwd->first_child;

    while (subDir != NULL) {
        if (strcmp(subDir->tree->string_buffer, arg) == 0) {
            printf("Directory with that name exists. Please provide another name.\n");
            return;
        }
        subDir = subDir->next;
    }

    // adding new directory
    struct tree_node *newSubDir = make_tree_node(arg);
    newSubDir->parent = cwd;
    struct list_node *newListNode = make_list_node(newSubDir, NULL);

    // putting new node in alphabetical order
    struct list_node *prev = NULL;
    if (subDir == NULL) {
        newListNode->next = cwd->first_child;
        cwd->first_child = newListNode;
    } else {
        while (subDir != NULL) {
            // TODO: use case insensitive compare
            if (strcmp(arg, subDir->tree->string_buffer) > 0) {
                // inserting in front
                newListNode->next = subDir->next;
                prev->next = newListNode;
                break;
            }
            prev = subDir;
            subDir = subDir->next;
        }
        if (subDir == NULL) {
            subDir->next = newListNode;
        }
    }
    printf("Directory added: %s", arg);
}

// prints all children of the directory cwd (not recursively)
void do_ls(struct tree_node *cwd) {
    printf("Listing Directories...\n");
    struct list_node *subDir = cwd -> first_child;
    while (subDir != NULL) {
        printf("%s", subDir ->tree -> string_buffer);
        subDir = subDir->next;
    }
}

// *checks whether cwd has a subdirectory named arg
// *if yes, the function returns the corresponding tree node (and become new working directory)
// *if no, prints an error message
// *handle cd and cd ..
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {

    // checks if cwd has a subdirectory named arg
    struct list_node *subDir = cwd -> first_child;

    while (subDir != NULL) {
        if (strcmp(subDir->tree->string_buffer, arg) == 0) {
            printf("Subdirectory exists: Entering!\n");
            subDir->tree = cwd;
            printf("Making subdirectory current working directory: name = %s\n", arg);
            printf("Returning current working directory: %s.\n", arg);
            return cwd;
        }
        subDir = subDir->next;
    }
    printf("Directory does not exist!\n");
    return NULL;
}

// *prints the prompt (e.g. /bar/baz/ >) in every iteration of the main loop
// *show all directories on the path in correct order
//void show_prompt(struct tree_node *cwd) {

//    while(cwd != NULL) {
//       printf(cwd->string_buffer);
       //show all directories on the path in correct order.
//    }
 //   printf("/");
//}

// *removes a node child from its parent node dir
// *take care to correctly support corner cases like the child being the only one
// *all memory occupied by the child should be freed
//void remove_child(struct tree_node *dir, struct tree_node *child) {
//    if (dir == NULL) {
//        printf("Current directory is empty!");
//    }
//    else if (dir -> child != NULL) {
//        free(child);
//    }
//}

// implement rmdir (follow same pattern as previous exercise)
// *if the specified directory is not empty, rmdir should fail with an error message
//void do_rmdir(struct tree_node *cwd, char *arg) {
//    if(cwd != NULL) {
//        printf("Specified directory is not empty!");
//   } else {
//        free(cwd);
//    }
//}

int main(void) {

    char directoryName[129] = "";

    printf("\nProgram Start... \n\n");

    // getting user input string
    // and splitting command and argument
    char inputString[129];
    char delimiter[] = " ";
    char *line;
    char *arg;
    struct tree_node *root = make_tree_node("root\0");
    //struct tree_node *cwd = make_tree_node("root\0");
    struct tree_node *cwd = root;

    printf("/%s >", directoryName);

    while (fgets(inputString, 128, stdin)) {

        // char * before strsep, set pointer to be original checkString
        // original checkString
        // then free memory 

        // gets argument and stores as arg
        line = malloc(strlen(inputString) + 1);
        strcpy(line, inputString);
        arg = strsep(&line, delimiter);
        arg = strsep(&line, delimiter);
        printf("your argument: %s\n", arg);

        printf("/%s >", directoryName);

        //printf("userInput:%s", inputString);

        if(strncmp(inputString, "exit", 4) == 0) {
            printf("Breaking...\n");
            break;
        }

        ////////////////////////////// HANDLING LS ////////////////////////////

        else if(strncmp(inputString, "ls ", 3) == 0) {
            printf("The ls command should be used without arguments.\n");
        }

        else if(strncmp(inputString, "ls", 2) == 0) {
            do_ls(cwd);
            printf("/%s >", directoryName);
        }

        ////////////////////////////// HANDING CD /////////////////////////////
        else if(strncmp(inputString, "cd ..", 5) == 0) {
            printf("Returning to previous directory.\n");
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "cd .", 4) == 0) {
            printf("Returning to current directory.\n");
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "cd ", 3) == 0) {
            do_cd(cwd, root, arg);
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "cd", 2) == 0) {
            printf("Returning to root directory.\n");
            printf("/%s >", directoryName);
        }

        /////////////////////////// HANDLING MKDIR /////////////////////////////
        else if(strncmp(inputString, "mkdir  ", 7) == 0) {
            printf("Please specify directory name that is not NULL: mkdir directoryName\n");
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "mkdir ", 6) == 0) {
            do_mkdir(cwd, arg);
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "mkdir", 5) == 0) {
            printf("Please specify directory name: mkdir directoryName\n");
            printf("/%s >", directoryName);
        }

        //////////////////////// HANDLING RMDIR /////////////////////////////////
        else if(strncmp(inputString, "rmdir  ", 7) == 0) {
            printf("Please specify directory name that is not NULL: rmdir directoryName\n");
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "rmdir ", 6) == 0) {
            printf("Removing Directory with name...\n");
            //
            printf("/%s >", directoryName);
        }
        else if(strncmp(inputString, "rmdir", 5) == 0) {
            printf("Please specify directory name: rmdir directoryName\n");
            printf("/%s >", directoryName);
        }
        else {
            printf("Unrecognised input: Please try again.\n");
            printf("/%s >", directoryName);
        }
    }

    printf("\nProgram Quit... \n\n");


    return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以使用:

while (fgets(inputString, 128, stdin)) {
    inputString[strlen(inputString)-1] = '\0';
    ...

我尝试使用我的更改,输出示例:

Program Start... 

/ >mkdir hello
your argument: hello
/ >Making Directory with name hello 
Directory added: hello/ >
相关问题