gpt4 book ai didi

c - 读取字符串中的输入

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:42 24 4
gpt4 key购买 nike

我正在使用创建电子邮件的函数,但我不知道如何在正文部分使用 fgets 读取用户的“输入”。我的代码如下:

void read_email_interactive(Email* email) {
printf("Subject: ");
fgets(email->subject,DEFAULT_MAX_FIELD,stdin);

printf("From: ");
fgets(email->from,DEFAULT_MAX_FIELD,stdin);

printf("To: ");
fgets(email->to,DEFAULT_MAX_FIELD,stdin);

printf("Body: ");
fgets(email->body,MAX_BODY,stdin);

printf("ID: ");
fgets(email->id,DEFAULT_MAX_FIELD,stdin);

有什么想法吗?谢谢!

最佳答案

假设文本的最大尺寸是可以接受的,下面的代码片段可以做到:

#define BODY_MAX_LEN (1234)

struct Email
{
char body[BODY_MAX_LEN + 1];
...
}

int main(void)
{
struct Email email = {0};

size_t s = 0;
while ((BODY_MAX_LEN > s) && fgets(email.body + s, BODY_MAX_LEN + 1 - s, stdin))
{
s = strlen(email.body);
if (!s || ('\n' != email.body[s - 1]))
{
break; /* EOF detected (user pressed Ctrl-D (UNIX)/Ctrl-Z (Window). */
}
}

if (ferror(stdin))
{
perror("fgets() failed");
exit(EXIT_FAILURE);
}

...

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

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