簡體   English   中英

用戶輸入 function C

[英]User input function C

用戶輸入 function C

大家好。 我從控制台讀取用戶輸入時遇到問題。 我正在嘗試實現 function 以塊的形式從控制台讀取和分配 memory

首要問題

第一個問題是我在 output 的開頭得到了一些工件。 對於輸入:

樣本輸入 1

樣本輸入 2

樣本輸入 3

樣本輸入 123

我得到:

_←樣本輸入1

_♂樣本輸入2

_|樣本輸入3

_ľ樣本輸入123

在調試器中char buffer[block_size]; 在執行fgets(buffer, block_size, stdin) = NULL之后,變量看起來很好。 我認為問題出現在strcat(input, buffer); . 我不知道為什么會這樣。 我猜我分配/重新分配 memory 是錯誤的。

第二期

第二個問題是控制台在Windows上最多輸出 4091 個字符,開頭有工件。 我嘗試過輸入 5000 或 8000 個“a”字符。

是否可以在不使我的代碼過於復雜的情況下增加輸入?

附加信息

我正在使用 Windows 10 Pro,版本:10.0.19044 Build 19044。

克萊恩 IDE。

MinGW 工具集。

C11 標准。

在 Linux Mint 機器上,我沒有得到工件,控制台 output 是 4096 個字符。

我沒有收到任何錯誤。

代碼

#include <stdio.h>
#include <malloc.h>
#include <string.h>

char *user_input();

int main() {


    char *x = user_input();

    printf("%s", x);
    
    return 0;
}

char *user_input() {

    const int block_size = 200;
    size_t temp_str_size, general_str_size = 0;
    char buffer[block_size];

    //allocates memory
    char *input = malloc(block_size * sizeof(char));

    do {

        //reads input to buffer
        if (fgets(buffer, block_size, stdin) != NULL) {


            temp_str_size = strlen(buffer);

            //reallocates whatever memory is needed for input 
            realloc(input, temp_str_size + general_str_size);
            
            //null check
            if (input == NULL) {
                printf("Unable to reallocate memory\n");
                return NULL;
            }
            
            
            strcat(input, buffer); // probably problem occurs here 

            // increases general string size for expanding memory reallocation
            general_str_size += temp_str_size;
        } else {
            return NULL;
        }
        
        
    } while (temp_str_size == block_size - 1);
    return input;
}

strcat(input, buffer)兩個參數都需要包含字符串。 input內容未初始化,因此具有不確定的值。 malloc之后使用input[0] = '\0'進行初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM