[英]Reading in a string of unknown length from the console
如果我想从命令行读取任意长度的字符串,那么最好的方法是什么?
目前我正在这样做:
char name_buffer [ 80 ];
int chars_read = 0;
while ( ( chars_read < 80 ) && ( !feof( stdin ) ) ) {
name_buffer [ chars_read ] = fgetc ( stdin );
chars_read++;
}
但是如果字符串超过80个字符,我该怎么办? 显然我可以将数组初始化为更大的数字,但我确信必须有更好的方法使用malloc或其他东西为数组提供更多空间?
任何提示都会很棒。
很久以前在网上的某个地方找到它,它真的很有用:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
printf("\nEnter a very very very long String value:");
if(pStr != NULL)
{
int c = EOF;
unsigned int i =0;
//accept user input until hit enter or end of file
while (( c = getchar() ) != '\n' && c != EOF)
{
pStr[i++]=(char)c;
//if i reached maximize size then realloc size
if(i == current_size)
{
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
}
pStr[i] = '\0';
printf("\nLong String value:%s \n\n",pStr);
//free it
free(pStr);
pStr = NULL;
}
return 0;
}
使用realloc()
分配缓冲区并在它满时扩展它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.