Reading an enter in a string

送分小仙女□ 提交于 2019-12-24 09:48:41

问题


I am working in a function to create an email, but I do not know how to read an "enter" from the user using fgets, in the body part. My code is the following one:

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);

Any Idea? Thank you!


回答1:


Assuming a maximum size of the text would be acceptable the following snippet would do:

#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);
  }

  ...



回答2:


After each

 printf("Subject: ");

Put in a

fflush(stdout);

So that the message appears



来源:https://stackoverflow.com/questions/48721053/reading-an-enter-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!