-1

I have a program here that allows a user to append a text file among other features but I've just shown 2 to keep it simple. The problem is, when the user selects, say option no. 1, the "Append" & "Enter a sentence:" comes out fine but the program quits at that...i.e, before the user can enter the sentence, it quits. How do I fix this ? (I've tried a simpler example with scanf & printf statements which work but here i'm working with a file and am unable to get the input required!)

int main()
{
    int choice;
    char c[2000];
    FILE *fp;

    printf("Welcome to my Text Editor!\n");
    printf("Enter the letter for the operation that you would like to carry out on the file\n");
    printf("1 - Append a word to end of file\n");
    printf("2 - Search for a word in the file\n");

    scanf ("%d", &choice);

    if (choice == 1)
    {       
        printf ("Append\n");
        fp=fopen("C:/Users/Asim/Desktop/random.txt","a");
        if(fp==NULL){
            printf("Error!");
            exit(1);
        }
        printf("Enter a sentence:\n");
        gets(c);
        fprintf(fp,"%s",c);
        fclose(fp);
    }
    else if (choice == 2)
    {
        printf ("Search");
    }
    else
    {
        printf ("Invalid choice!");
    }
}
ilim
  • 4,477
  • 7
  • 27
  • 46
Asimo96
  • 25
  • 4
  • Your scanf is keeping the \n in the buffer, replace it with a getc perhaps, changing choice to char ? – Gar Jun 10 '16 at 08:32
  • Some flavour of this question has been asked thousand times before, please do some research before asking. Also please don't use gets, that function has been flagged at outdated for the past 17 years. Why are you learning C from sources that are older than 17 years? – Lundin Jun 10 '16 at 08:39

1 Answers1

0

When the user enters a choice, presumably they hit enter before you start processing their choice. Then, your use of gets function causes your program to interpret that '\n' as input. You may use scanf instead with format string "%s" to read into a buffer instead of gets.

...
printf("Enter a sentence:\n");
scanf("%s", c);
fprintf(fp,"%s", c);
...

Alternatively, if you insist on keeping gets, a messy solution could be using getc right after you call scanf for choice, or to read an extra char in that scanf call, to process '\n'.

...
scanf ("%d%c", &choice);
getc();
...
ilim
  • 4,477
  • 7
  • 27
  • 46