Program crashes when I try to enter input when using breakpoints

ghz 8months ago ⋅ 105 views

My goal is to enter input into my C program when using breakpoints. Worked fine until I got to the breakpoint for scanf() where I tried entering input into the terminal but the program stopped working and the debugger window terminal closed. I tried entering text into the debug console and terminal, both did not work. Anyone know how/where to enter input to scanf when using breakpoints in vscode for c?

int main(){

    int numAttempts = 0;
    FILE* fp;
    char fileName[1024];

    while(numAttempts < 3){
        printf("Enter input file: ");
        scanf("%s", fileName);
        fp = fopen(fileName, "r");

        if (fp == NULL){
            fprintf(stderr, "ERROR: Input file %s not opened \n", fileName);
            numAttempts++;
            if(numAttempts >= 3){
                fprintf(stderr, "ERROR: too many failures opening input file");
                exit(0);
            }
        }
        else{
            break;
        }
    } 

Answers

When debugging a C program using breakpoints in Visual Studio Code, inputting values to scanf() might seem problematic because the debugger window's terminal doesn't readily accept input while the program is paused at a breakpoint. However, you can provide input in a couple of different ways:

  1. Debug Console: You can input values directly into the debug console while the program is paused at the breakpoint. You should see a prompt in the debug console. Type the desired input and press Enter.

  2. Modify Code to Use Command Line Arguments: Alternatively, you can modify your code to accept command-line arguments instead of using scanf(). This way, you can run your program with the required inputs from the terminal before it starts execution.

Here's an example of how you could modify your code to use command-line arguments:

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

int main(int argc, char *argv[]) {
    FILE *fp;
    char *fileName;

    // Check if the filename is provided as a command-line argument
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <input_file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    fileName = argv[1];

    fp = fopen(fileName, "r");
    if (fp == NULL) {
        fprintf(stderr, "ERROR: Input file %s not opened\n", fileName);
        exit(EXIT_FAILURE);
    }

    printf("Input file %s opened successfully.\n", fileName);

    // Rest of your code here...

    fclose(fp);
    return 0;
}

With this modification, you would run your program from the terminal like this:

./your_program input.txt

Replace your_program with the name of your compiled executable and input.txt with the name of the file you want to open. This way, you don't need to worry about inputting values during debugging sessions.