[英]User input 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.