gpt4 book ai didi

c - 如何为未知长度的输入字符串分配内存?

转载 作者:行者123 更新时间:2023-12-04 09:06:45 25 4
gpt4 key购买 nike

这是结构:

typedef struct _friend {
char *firstname;
char *lastname;
char birthdate[9];
} friend;

我对如何让用户输入一个字符串并将其作为 firstname(或 lastname)放在 friend 结构中感到困惑).另外,如果我使用 fgets 时用户输入了超过 256 个字符怎么办?这是我目前所拥有的...

friend *f = (friend *)malloc(sizeof(friend));  //initialize f pointer to friend
char *str;

fgets(str,256,stdin);
f->firstname = (char*)malloc(sizeof(char)*(strlen(str)+1));
strcpy(f->firstname,str);

最佳答案

好吧,由于 stdin 是一个缓冲输入,您可以使用 fgetc 逐个字符地读取输入,直到遇到换行符或 EOF。也许您正在寻找这样的东西:

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

struct friend {
char *firstname;
char *lastname;
char birthdate[9];
};

static char *read_line(FILE *f)
{
char *r = NULL;
char *p = r;
char *e = p;
int c;

while ((c = fgetc(f)) != EOF) {
if (p >= e) {
size_t l = e > r ? (size_t)(e - r) : 32u;
char *x = realloc(r, l);
if (!x) {
free(r);
r = NULL;
goto out;
}
p = x + (p - r);
e = x + l;
r = x;
}
if (c != '\n') {
*p++ = (char)c;
} else {
*p++ = '\0';
goto out;
}
}
if (ferror(f) != 0) {
free(r);
r = NULL;
}
out:
return r;
}

int main(void)
{
struct friend f;

memset(&f, 0, sizeof(struct friend));

printf("Please enter your first name: ");
fflush(stdout);
f.firstname = read_line(stdin);
if (!f.firstname)
goto on_error;
printf("Please enter your last name: ");
fflush(stdout);
f.lastname = read_line(stdin);
if (!f.lastname)
goto on_error;

printf("You first name is: %s\n", f.firstname);
printf("Your last name is: %s\n", f.lastname);

free(f.firstname);
free(f.lastname);
return EXIT_SUCCESS;

on_error:
perror("read_line");
free(f.firstname);
free(f.lastname);
return EXIT_FAILURE;
}

关于c - 如何为未知长度的输入字符串分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12878240/

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