0

So what I'm trying to do is input choice a and then input a file name to open. But instead, it is using the input for the switch statement as "gets" as well as for the menu choice. Down below is what I have so far. I have tried swapping out getc with "gets" that didn't work. I tried putting a "\n" in the scanf. That didn't work.

This is what it's supposed to look like:

This is what it's supposed to look like

This is what what I have now:

This is what what I have now

char choice = 'a';

//Display menu
printf("a. Enter file location(fullpath)\n");
printf("b. Display the labyrinth\n");
printf("c. Enter a box size\n");
printf("d. Enter a box size\n");
printf("e. Valdate path\n");
printf("f. exit\n");
scanf("%c\n", &choice);

if (choice == 'a')
{
    
    char inputFile[1000], ch;

    //a).Read fullpath for the input file

    getc(inputFile);
    FILE* file;
    file = fopen(inputFile, "r");
    if (file == NULL)
    {
        printf("Failed to open file");
        printf("Goodbye");
        return 0;
    }
    else
    {
        printf("File opened successfully\n");
    }
    
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Cipher
  • 1
  • 1
    `gets()` doesn't get ignored -- it sees the `'n'` left in `stdin` after `scanf("%c\n", &choice);` and takes that as the input. Now go read [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/q/1694036/3422102) – David C. Rankin Nov 26 '20 at 07:37
  • Your code doesn't use `gets()` (which is a [Good Thing™](https://stackoverflow.com/q/1694036/15168)). It uses `getc()`. Note that the newline at the end of the format string in `scanf("%c\n", &choice)` means that `scanf()` does not return until you type some non-white-space character after the letter choosing what you want to do. Specifically, it continues to read newlines, so hitting the return key doesn't finish the `scanf()`. You probably want to use `if (scanf(" %c", &choice) == 1) { …OK… } else {…Failed!… }` to read the input. The leading space skips over any remaining white space. – Jonathan Leffler Nov 26 '20 at 07:43
  • Suggest `char choice[64];` then `fgets (choice, sizeof choice, stdin)` and then use `if (*choice == 'a')` That way even if the user enters `"alligators"`, you are covered, a complete line of input is read and nothing remains in `stdin` just waiting to bite you on your next input. (and correction to the comment above it should be "it sees the `'\n'` ...") – David C. Rankin Nov 26 '20 at 07:44
  • You might then legitimately use a loop such as `int c; while ((c = get()) != EOF && c != '\n') ;` to read all the data up to the next newline. A single `getc()` will give grief if the user types `aa` (and return — or `alligators` and return) instead of just `a`. – Jonathan Leffler Nov 26 '20 at 07:44

0 Answers0