我认为使用一个适当大的中间缓冲区,并将字符串输入其中fgets
或通过将字符串长度限制为最大缓冲区大小来实现其他功能。稍后当输入字符串时,。计算字符串长度并分配一个字符串大小的缓冲区并将其复制到新分配的缓冲区中。旧的大缓冲区可以重新用于此类输入。
你可以做:
fgets (buffer, BUFSIZ, stdin);
or
scanf ("%128[^\n]%*c", buffer);
这里你可以指定缓冲区长度 128 字节为%128..
并且还包括字符串中的所有空格。
然后计算长度并分配新的缓冲区:
len = strlen (buffer);
string = malloc (sizeof (char) * len + 1);
strcpy (string, buffer);
.
.
.
free (string);
EDIT
这是我解决的一种方法:
#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;
}
您需要修复代码以停止在某些情况下崩溃,但这应该可以回答您的问题。