-1

I'm working with files and trying to create one with user's text input, but some of the input must allow different words with spaces between. I've been looking for solutions here, I suppose the best option is to use fgets but it only works for text input while subject input only prints the text in the file after two words, I would like to know how to print in the file the whole subject input.

THANKS!!

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

int main()
{
    int id=0;
    char to[20], from[20], date[10], subject[40], text[1000];
    FILE *fp;

    fp = fopen("outbox/email.txt","w");

    printf("\nTo: ");
    scanf("%s",&to);
    printf("\nFrom: ");
    scanf("%s", &from);
    printf("\nID: %d\n", id);
    printf("\nDate: ");
    scanf("%s", &date);
    printf("\nSubject: ");
    scanf("%s",&subject);
    printf("\nText: ");
    scanf("%s",&text);

    fprintf(fp,"To: %s     ",to);
    fprintf(fp, "From: %s     ", from);
    fprintf(fp, "ID: %d     ", id);
    fprintf(fp, "Date: %s     ", date);
    fgets(subject,40,stdin);
    fprintf(fp, "Subject: %s     ", subject);
    fgets(text,1000,stdin);
    fprintf(fp, "Text: %s     ", text);

    fclose(fp);

 return 0;
}

1 Answers1

0

scanf("%s", str) reads only one word. fgets(str, sizeof str, stdin) reads a whole line. It seems to me that you want to read in a whole line for each header item, since they are all usually made out of multiple words. So use fgets() everywhere.

Also, the sizes you use for the strings are quite small. It's easy to have an email address that is longer than 19 characters for example.

G. Sliepen
  • 7,637
  • 1
  • 15
  • 31