1

My program is designed to sort records in a text file, but my main issue is getting the main function to ask the user if he would like to run the program again to read and write another file. My program right now, when the user enters 1 to run again, skips the first question to enter the program to read. Why is that? I appreciate the help! Here is my main function only: The program compiles only during the first run.

int main()
{
    int    fieldCount = 0;
    int    lineCount = 0;
    char file[STR_LEN];
    char   filepath[STR_LEN];
    char** fields = NULL;
    char** lines = NULL;
    int    recCount = 0;
    Person **sortedRecs = NULL;
    int x;

    do {
        printf("Enter path of the file to read: ");
        gets(filepath);
        printf("Enter path to copy to: ");
        gets(file);
        fields = readFieldsDynamic(filepath, &fieldCount);
        lines = readLinesDynamic(filepath, &lineCount);
        recCount = getPersons(fields, fieldCount, &sortedRecs);
        if (recCount && lines && sortedRecs && (recCount <= lineCount)) {
            writeRecsToFile(file, sortedRecs, recCount, lines, lineCount);
            printf("Sorted records are written in %s\n", file);
        }
        if (fields) {
            freePointerToChars(fields, fieldCount);
        }
        if (lines) {
            freePointerToChars(lines, lineCount);
        }
        if (sortedRecs) {
            freeRecs(sortedRecs, recCount);
        }
        printf("Enter 1 to run program again: ");
        scanf("%d%*c", &x);
    } while (x == 1);
    return 0;
}
Puck
  • 2,080
  • 4
  • 19
  • 30
Benny
  • 15
  • 1
  • 7

3 Answers3

1

What you can do is add a while loop to "eat up" all the newlines left in stdin stream to prevent the next getchar to not block for real user input.

while ((ch=getchar()) != EOF && ch != '\n')
    ;

Also please don't use gets in your code. Try fgets instead.

Linus
  • 1,516
  • 17
  • 35
1

You need to keep a space before %c.

int main()
{
  char ch;
  do
  {
      something();
      printf("\nDo you want to continue?");
      scanf(" %c", &ch);
  }while(ch=='y');
  return 0;
}
0

This answer is based on your output looking something like:

Enter path of the file to read: /my/input/here/
Enter path to copy to: /blah/copy/here/
Enter 1 to run program again: 1
Enter path of the file to read: 
Enter path to copy to: help/I/cant/type/in/the/above/field

My understanding is your program is probably carrying over the newlines between loops.

I've had similar problems in C++, and placing cin.get() after an input fixed it. I'm not certain of the C equivalent.

DeepDeadpool
  • 1,441
  • 12
  • 36