问题
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