1

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!

15
  • 1
    fgets() does read the new-line!
    – alk
    Feb 10, 2018 at 13:01
  • Yes but in a body message the user usually press several "enters", but here if I press the enter it is going to the next instruction
    – JIAN CHEN
    Feb 10, 2018 at 13:02
  • I see, the body part consists od multiple lines - and you want to read them as a chunk? Feb 10, 2018 at 13:02
  • 1
    The idea is to consider reading the body and when user enters a blank line you will udnerstand that the body is complete let's move to the next section. This you can follow for other commands also. Feb 10, 2018 at 13:04
  • 1
    @JIANCHEN.: Just said the solution. Redesign the code little bit to incorporate blank lines as end of sections. Feb 10, 2018 at 13:05

2 Answers 2

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

  ...
1
  • @usr2564301: Definitely. Thanks for pointing this out. Corrected.
    – alk
    Feb 17, 2018 at 8:33
1

After each

 printf("Subject: ");

Put in a

fflush(stdout);

So that the message appears

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.