首页 文章

对来自getline的输入进行标记

提问于
浏览
1

我正在尝试使用getline()从键盘获取输入,将其存储在字符串中,对其进行标记,然后打印标记 . 当我运行它时,我在最后一次迭代(处理来自输入的最后一个令牌的迭代)上得到一个Segmentation Fault错误 .

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

////////////////////////
// Main Method        //
////////////////////////
void main() {
    system("clear");
    int ShInUse = 1; // Represents if shell is in use

    char curpath[1024];   // holds current path to print with prompt
    char *UserCommand = NULL;
    size_t combytes = 100;
    UserCommand = (char *) malloc(combytes);
    char *tok;

    // Main loop that shell uses //
    while (ShInUse == 1) {
        getcwd(curpath, sizeof(curpath)); // Store initial working dir
        printf("gash:%s>", curpath);   // print prompt

        getline(&UserCommand, &combytes, stdin);
        tok = strtok(UserCommand, " \n");   // Tokenize input
        if (tok == NULL ) {
            printf("Enter a command.\n");
        } else {
            // Exit command //
            if (strcmp(tok, "exit") == 0) {
                ShInUse = 0;
            } else {
                while (tok != NULL ) {
                    printf("You entered a command.\n");
                    printf("tok: %s\n", tok);
                    tok = strtok(NULL, " \n");
                }
            }
        }
    }
    free(UserCommand);
}

关于可能导致这种情况的任何想法?目前调试不是我的选择 .

2 回答

  • 0

    我测试了你的代码:

    #define _POSIX_C_SOURCE 200809L
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char *UserCommand = NULL;
        size_t combytes = 100;
        UserCommand = (char *) malloc(combytes);
        char *tok;
        while(getline(&UserCommand, &combytes, stdin) != EOF)
        {
        tok = strtok(UserCommand, " \n");    // Tokenize input
        if (tok != NULL) {
            while(tok != NULL) {
            printf("%s\n", tok);
            tok = strtok(NULL, " \n");
            }
        }
        }
        return 0;
    }
    

    它适用于我所做的所有测试 - 包括将源文件作为输入传递,写入相当长的行等等 .

    所以我的结论是你可能在代码中有一些段错误 .

  • 3

    也不是答案,只是编程风格的另一种选择:

    每当我有像你这样的标记化循环时,我更喜欢像这样构造它们:

    for( tok = strtok( UserCommand, " \n" );
         tok != NULL;
         tok = strtok( NULL, " \n" ) )
    {
       printf( "%s\n", tok );
    }
    

    这使得两个 strtok() 调用紧密相连,只需要编写一次 NULL 测试 . 你的方式很好,这只是另一种选择 . 祝好运!

相关问题