我已经在c中实现了自己的动态数组数据结构,现在我正在寻找一种在不失去动态性的情况下填充它们的方法。
如果我写类似
char str[ANY_CONSTANT];
fgets(str, ANY_CONSTANT, stdin);
我可以传递给程序的元素数量是在编译时定义的,而这正是我不想发生的事情。
如果我写类似的东西
char str[ANY_CONSTANT];
scanf("%s", &str)
我也有同样的情况。有没有固定尺寸的键盘输入数据功能?预先感谢!
答案 0 :(得分:2)
您可以尝试使用POSIX getline
功能:
char *buf = NULL;
size_t buflen = 0;
ssize_t readlen = getline(&buf, &buflen, stdin);
/* buf points to the allocated buffer containing the input
buflen specifies the allocated size of the buffer
readlen specifies the number of bytes actually read */
getline从控制台读取整行,并根据需要重新分配缓冲区以存储整行。