使用与fgets用C动态大小的输入 [英] Input of dynamic size using fgets in C
问题描述
我想有一个字符串(可以包含空格)作为输入。我想这样做动态分配。
我的程序的结构有点像这样。
I want to have a string(can contain spaces) as input. I want to do dynamic allocation. Structure of my program is somewhat like this.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct msgclient
{
int msglen;
int msgtype;
char *cp;
}M1;
int main()
{
M1 *m;
m=malloc(sizeof(M1));
m->msglen=5;
m->msgtype=6;
printf("Enter\t");
fgets(m->cp,50,stdin); //here
// m->cp[strlen(m->cp)]='\0';
printf("\n%d\n%d\n",m->msglen,m->msgtype);
fputs(m->cp,stdout);
return 0;
}
我想知道如何获得输入。是否有任何方式与fgets的第二个参数是动态的?
I want to know how to get input. Is there any way that the second argument of fgets be dynamic?
推荐答案
使用的函数getline(3)的-instead 与fgets(3) - 它读取一个动态分配的行
Use getline(3) -instead of fgets(3)- which reads a dynamically allocated line.
typedef struct msgclient {
ssize_t msglen;
int msgtype;
char *cp;
}M1;
然后在主
函数
M1 *m;
m=malloc(sizeof(M1));
if (!m) { perror("malloc"); exit(EXIT_FAILURE); };
m->msglen=0;
m->msgtype=6;
m->cp = NULL;
printf("Enter\t");
fflush(stdout);
size_t msgsize = 0;
m->msglen = getline(&msg->cp, &msgsize, stdin);
您可以考虑添加缓冲(即 msgsize
)的分配大小为结构msgclient
的附加字段
you might consider adding the allocated size of the buffer (i.e. msgsize
) as an additional field of struct msgclient
注意,您或许可以考虑使用 GNU的readline 。它提供了编辑和完成设施(从终端读取时)。
Notice that you might perhaps consider using GNU readline. It offers edition and completion facilities (when reading from a terminal).
这篇关于使用与fgets用C动态大小的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!