gpt4 book ai didi

c - 在 C 中读取字符串

转载 作者:行者123 更新时间:2023-12-01 11:56:07 26 4
gpt4 key购买 nike

如果我使用 C gets(),并且我正在从用户那里读取一个字符串,但我不知道我需要多大的缓冲区,而且输入可能非常大。有没有一种方法可以确定用户输入的字符串有多大,然后分配内存然后将其放入变量中?或者至少是一种在不知道输入有多大的情况下接受输入的方法,有可能它不适合我已经分配的缓冲区。

最佳答案

我认为使用一个适当大的中间缓冲区,并通过将字符串长度限制为最大缓冲区大小,使用 fgets 或其他函数将字符串输入其中。稍后当输入字符串时,。计算字符串长度并分配字符串大小的缓冲区并将其复制到新分配的缓冲区中。旧的大缓冲区可以重新用于此类输入。

你可以这样做:

fgets(缓冲区、BUFSIZ、标准输入);

scanf("%128[^\n]%*c", 缓冲区);

在这里您可以将缓冲区长度指定为 128 字节作为 %128.. 并且还包括字符串中的所有空格。

然后计算长度并分配新的缓冲区:

len = strlen (buffer);
string = malloc (sizeof (char) * len + 1);
strcpy (string, buffer);
.
.
.
free (string);

编辑

这是我的一种解决方法:

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

int main (void)
{
char *buffer[10]; /* temporary buffers 10 nos, or make this dynamically allocated */
char *main_str; /* The main string to work with after input */
int k, i=0, n, retval;

while (1)
{
buffer[i] = malloc (sizeof (char) * 16); /* allocate buffer size 16 */
scanf ("%15[^\n]%n", buffer[i], &n); /* input length 15 string + 1 byte for null */
if (n<16) /* Buffer is not filled and end of string reached */
break;
n=0; /* reinitialize n=0 for next iteration. to make the process work if the length of the string is exactly the sizeof the buffer */
i++;
}
/* need to fix the while loop so that the buffer array does not overflow and protect it from doing so */

/* allocate buffer of exact size of the string */
main_str = malloc (sizeof (char) * 16 * i + strlen (buffer[i]));

/* copy the segmented string into the main string to be worked with
* and free the buffers
*/
strcpy (main_str, "");
for (k=0; k<=i; k++)
{
strcat (main_str, buffer[k]);
free (buffer[k]);
}

/* work with main string */
printf ("\n%s", main_str);

/* free main string */
free (main_str);

return 0;
}

您需要修复代码以在某些情况下停止崩溃,但这应该可以回答您的问题。

关于c - 在 C 中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7148778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com