由换行符

时间:2017-04-02 15:29:36

标签: c segmentation-fault fgets

我正在使用fgets()从stdin获取输入。我希望fgets()继续从用户获取输入,直到执行 CTRL + D (EOF)命令。到达文件末尾后,应打印用户输入数组。

当用户在两行输入之间输入换行符(\ n)时,当我尝试打印数组时会发生分段错误。除了教程点描述之外,我已经查看了类似的StackOverflow帖子,但我仍然可以帮助解决这个问题。

int main(int argc, char **argv) {
    // Maximum input size
    int input_size=1024;
    // Standard Input array
    char standard_input[input_size];
    // Input array
    char **input=malloc(input_size*sizeof(char*));
    // Integer to track input size
    int size=0;

    // Handle the input
    while(fgets(standard_input, input_size, stdin)){
        // Delimiter
        char delimit[]=" \n";
        // Node string
        char *my_node;
        my_node=strtok(standard_input, delimit);
        // Process the input from stdin
        for(int i=0; my_node!=NULL; i++){
            input[i]=malloc(strlen(my_node)+1);
            strcpy(input[i], my_node);
            // Special input processing
            // Ignore non-alpha entries
            // Convert uppercase to lowercase
            bool valid=true;
            for(int j=0; j<strlen(input[i]); j++){
                // Ignore non-alpha entries
                if(!isalpha(input[i][j]))
                    valid=false;
                // Convert uppercase to lowercase
                else
                    input[i][j]=tolower(input[i][j]);
            }
            my_node=strtok(NULL, delimit);
            // If the element was found to be invalid due to the presence
            // of non-alpha characters, remove it
            if(!valid){
                free(input[i]);
                i--;
            }
            else if(valid)
                size++;
        }
    }
    for(int i=0; i<size; i++)
        printf("%s\n", input[i]);
    // Memory cleanup
    // Free input to avoid memory leaks
    for(int i=0; i<size; i++){
        free(input[i]);
    }
    free(input);
    return 0; // return 0 to match the return type of the main function
}

0 个答案:

没有答案
相关问题