Skip to content
Advertisement

Why does running C code in Vim skip scanf()?

I’m using neovim in arch linux with the gcc C compiler, this is what I use in my .vimrc to compile and run

map <F5> :w <CR> :!gcc % -o %< && ./%< <CR>

The issue is that my code will run fine but any scanf() functions won’t prompt an input and will be ignored as the program will runs. Even after compiling with vim then running in a separate zsh terminal it will allow me to enter the values when running the code with ./x

I apologise in advance, I’m new to vim and wanted to use this to speed up my workflow.

The following code exhibits the issue:

#include <stdio.h>

int main()
{
    char Team1[20]; 
    char Team2[20]; 
    int team1Score, team2Score; 
    printf("Please enter the name of team one: ");
    scanf("%s", Team1);
    printf("Please enter the name of team two: ");
    scanf("%s", Team2);
    printf("Please enter the score for %s: ", Team1); 
    scanf("%d", & team1Score); 
    printf("Please enter the score for %s: ", Team2); 
    scanf("%d", & team2Score);
    if (team1Score > team2Score)
    {
        printf("%s scores 3 points and %s scores 0 points", Team1, Team2 );
    }
    else
      if (team1Score < team2Score) 
        {
            printf("%s scores 3 points and %s scores 0 points", Team2, Team1 ); 
        }
        else
    {
            printf("Both %s and %s score 1 point", Team1, Team2); 
    }
    return 0;
}

Advertisement

Answer

The fault is probably not in your program, but the way vim executes it. If you check the documentation of :! command then you can see the following:

The command runs in a non-interactive shell connected to a pipe (not a terminal).

Non-interactive shell means a shell, which does not allow user commands to be entered. Your program will not read scanf input from the terminal, but from the pipe which was created by vim.

If you are using a recent version of vim (8.0 or later, if I’m right) or neovim then you can use the :term command to open a terminal. In that terminal you will be able to enter user input.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement