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;
}
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.
Related
I can't properly run/debug my code in VS Code using the C language. I've installed C/C++ package on VSC, Mingw & applied the path for Mingw. All my files are running .c format as well.
Only the last part of my code keeps crashing in VSC, when I run this same code on website compilers, it works!
Here is my code:
#include <stdio.h>
int main(void) {
int num1;
int num2;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d ", num1 + num2);
return 0;
}
That last printf is where VSC just shuts down the output window, so I never get to see the end result of my code. Anyone have any solutions to fix this? It'd be greatly appreciated!
When you run your console program from Visual Studio, it opens a terminal window, runs the program and the terminal window closes automatically when the program exits. This is a classic problem with the Microsoft Windows platform that they do not seem to care about despite millions of newbie programmers like you experiencing the same problem.
If you open the terminal window yourself, by running the CMD command from the start menu, you will be able to run your program manually after changing the current directory to that of the program binary.
To prevent the terminal window from closing immediately when running directly from Visual Studio, you should add 2 getchar(); statements before returning from main() to wait for user input and get a chance to see the output. Just reading a single byte with getchar() will not suffice because it will just read the pending newline entered by the user in response to the second prompt.
Also note that it is preferable to output a trailing newline to ensure the output is properly flushed on some legacy systems:
printf("Answer: %d\n", num1 + num2);
Here is a modified program you can test:
#include <stdio.h>
int main(void) {
int num1 = 0, num2 = 0;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d\n", num1 + num2);
getchar(); // read the pending newline
getchar(); // read at least another byte from the user.
return 0;
}
run you program from the console:
In the search box type cmd
cd \path_to_your_executable
run your program.
The program is supposed to get user first name and last name and then print them as last name, first name. The program stops immediately after the second input. I tried fflush (stdout) but that didn't seem to work (I might have done it incorrectly).
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
int main()
{
char First[30], Last[30];
printf("Please type in your First Name: ");
scanf("%s",&First);
fflush(stdout);
printf("Please type in your Last Name: ");
scanf("%s",&Last);
printf("%s %s", Last, First);
printf("pause");
return 0;
}
C++ version of your program :
#include <iostream>
using namespace std;
int main()
{
string first, last;
cerr << "Please type in your First Name: ";
if (! (cin >> firs))
return -1;
cerr << "Please type in your Last Name: ";
if (! (cin >> last))
return -1;
cout << last << ' ' << first << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra i.cc
pi#raspberrypi:/tmp $ ./a.out
Please type in your First Name: aze
Please type in your Last Name: qsd
qsd aze
pi#raspberrypi:/tmp $
I check names was enter (no EOF), I use cerr to be sure to flush the messages without writing endl
And the C version :
#include <stdio.h>
int main()
{
char first[30], last[30];
fprintf(stderr, "Please type in your First Name: ");
if (scanf("%29s", first) != 1)
return -1;
fprintf(stderr, "Please type in your Last Name: ");
if (scanf("%29s", last) != 1)
return -1;
printf("%s %s\n", last, first);
return 0;
}
Compilation and execution:
pi#raspberrypi:/tmp $ gcc -pedantic -Wextra i.c
pi#raspberrypi:/tmp $ ./a.out
Please type in your First Name: aze
Please type in your Last Name: qsd
qsd aze
I limit the size in the scanf to not write out of the arrays, I check scanf was able to read the names, I also use stderr to be sure to flush the message without writing '\n'
first and last are array, it is useless to use '&' in the scanf to give their address
Note these versions do not allow to enter composed names using spaces, to allow that all the line need to be read
It helps to think about the purpose of the fflush() call. There is pending data that you want the user to see so they know what to type.
Let us consider the first query (printf, scanf, flush). The printf() puts data into a buffer. The scanf() then reads the user's response. The flush() won't execute until after the user has typed something.
Those three calls are in the wrong order. I'll leave fixing that as an exercise for the reader.
Now consider the next query (printf, scanf). The printf() puts data into a buffer. The scanf() reads the user's response, but the user won't yet have seen the "... Last Name:" prompt.
Clearly there is also an error in that block. Again, I'll leave fixing that as an exercise for the reader. Hint: if you fixed the first error that should help you understand the second.
By the way, scanf() doesn't guard against overflowing the First[] and Last[] arrays. That isn't necessary to answer your original question, but I mention it because even after you have fixed the code it will remain unsafe.
The fflush(stdout); you have doesn't help because it's too early in the code as it doesn't help with flushing the latter printfs.
You could use \n to flush as well. But this may not work if your output device isn't interactive e.g. redirected to a file.
You also have another problem with scanf() format specifiers: First and Last, being arrays, decay into pointers when passed to scanf. So you are passing the wrong type of arguments to scanf - just drop the &'s from scanf calls.
So your program could simply be:
#include <stdio.h>
int main(void)
{
char First[30], Last[30];
printf("Please type in your First Name: ");
scanf("%s", First);
fflush(stdout);
printf("Please type in your Last Name: ");
scanf("%s", Last);
fflush(stdout);
printf("%s %s\n", Last, First);
fflush(stdout);
getchar();
return 0;
}
All the fflush(stdout) calls may not be necessary if you could use \n in all printf calls because you're likely using an interactive terminal.
If you are using C++, you should really be using iostream for I/O. If nothing else, scanf is a terrible, has many problems, and should be avoided.
I want to learn C. I would like to get my notepad++ to compile and run my .c files. I have done what is needed to be done. I am using MinGW and have added the plugin. I added this prompt:
npp_save
cd "$(CURRENT_DIRECTORY)"
gcc -Wall -Werror "$(FILE_NAME)" -o $(NAME_PART) -march=native -O3
NPP_RUN $(NAME_PART)
but whenever I go to compile and run, a command prompt appears and takes all the input. But when the time comes to show me an output command prompt closes out. Also there is no output on the console embedded in the notepad++ either. I then have to use Windows cmd to execute. Can someone please help me. I am a beginner.
for instance, take a look at this:
#include <stdio.h>
/* Note: Program assumes years are in the same century. */
int main(void)
{
int month1, day1, year1, month2, day2, year2;
int first_earlier = 0;
printf("Enter first date (mm/dd/yy): ");
scanf("%d/%d/%d", &month1, &day1, &year1);
printf("Enter second date (mm/dd/yy): ");
scanf("%d/%d/%d", &month2, &day2, &year2);
if (year1 != year2)
first_earlier = year1 < year2;
else if (month1 != month2)
first_earlier = month1 < month2;
else
first_earlier = day1 < day2;
if (first_earlier)
printf("%d/%d/%d is earlier than %d/%d/%d\n", month1, day1, year1, month2, day2, year2);
else
printf("%d/%d/%d is earlier than %d/%d/%d\n",month2, day2, year2, month1, day1, year1);
getchar();
return 0;
}
when pressing F6, the command prompt appears, it asks dates and when pressing enter after entering the second date prompt closes without showing me an output anywhere.
First of all, g++ is the C++ compiler. If you have C code, then you have to
use gcc to compile C code.
I don't really understand what you mean by a command prompt appears and takes
all the input, but judging from the behaviour that the console closes
immediately, then this is because the console closes right after the program
exits.
When making a double-click on an (console) executable, a terminal is spawned and
it executes your program (not the command line). Normal behaviour of terminals is that when the
executed program exists, the terminal closes. This also would happen when
launching the program through your IDE.
As you can see, if you open a terminal and execute it from there, the terminal
stays open, because the command line is still active1.
If you want to launch a program via double-click or IDE, then you have to make
sure that your program doesn't exit right away. An easy way to do this is by
making the user wait for an input.
#include <stdio.h>
int main(void)
{
printf("hello world\n");
puts("Press Enter to continue...");
getchar();
return 0;
}
Here the getchar would wait for user input and it would exit after the user hits ENTER. This is a workaround for launching console programs via
double-click and IDEs. However I think this is bad practice, the correct way
would be to start a terminal yourself and execute your program yourself.
Many terminals have the option that they don't close immediately when the
running program ends. For that you should be able to check the settings of the
terminal. Sometimes IDEs have also a checkbox in the settings that you have to
check so that the terminal doesn't close right away.
edit
The reason why getchar at the end does not wait is because of the previous
scanf.
When you enter something in the command line, a newline ('\n') is also added
to the input stream.
scanf("%d/%d/%d", &month2, &day2, &year2);
If the format is correct, scanf will consume all input but leave behind the
newline in the input buffer. The last getchar() will consume the newline that
is already in the buffer, and because of that it doesn't wait for further user
input.
You have to clear your input buffer. Add this function before the main:
void clear_stdin(void)
{
int c;
while((c = getchar()) != '\n' && c != EOF);
}
The call it after the scanf calls:
printf("Enter first date (mm/dd/yy): ");
scanf("%d/%d/%d", &month1, &day1, &year1);
clear_stdin();
printf("Enter second date (mm/dd/yy): ");
scanf("%d/%d/%d", &month2, &day2, &year2);
clear_stdin();
Now that the input buffer is cleared, the last getchar will wait for more user
input and you program will block until you press ENTER.
Fotenotes
1Note that a terminal (console) is not the same as the command
line. The terminal is the program that displays the text and allow users to
type with the keyboard. A command line is just a program that allows you to
enter commands and start programs. In Windows the command line is cmd.exe
called command line, it is mostly found in C:\Windows\System32.
The default settings are that when you open a terminal without telling which
command to execute, it will automatically open a command line, in Windows would
be cmd.exe by default.
I have written a simple "hello, world" program from here http://www.cprogramming.com/tutorial/c/lesson1.html cprogramming: lesson 1, the output is shown then the terminal prompt shows up in the following one. When executing another program:
#include <stdio.h>
main()
{
int age;
printf("How old are you?");
scanf("%d", &age);
if (age <= 20)
{
printf("You are still young");
}
else if (age >= 20)
printf("You are not that young anymore!");
else if (age >= 30)
printf("Hello young man!\n");
getchar();
return 0;
}
The output is shown in the same line as the terminal prompt in Gnome Terminal 3.6.1 on Ubuntu 13.10. I just don't know if this a code issue or is it related to the terminal only.
Alignment can be done using escape sequences.
In your case u need to use \n for new line
Add a newline character after each of your printf's
example:
int age;
printf("How old are you?\n");
scanf("%d", &age);
I have a simple program test which gets a number as input and prints the same on console.
#include<stdio.h>
int main(void)
{
int i;
printf("Test Pgm \n");
printf("Enter a no:");
scanf("%d",&i);
printf("No Inputted:%d \n",i);
return 0;
}
//The above program lies on 10.220.5.xx (different machine)
##gcc -o test test.c
On invoking the test pgm frm another machine over ssh , I don't get any prompt on the machine where im executing.
$ ssh user#10.220.3.xx '/home/user/test'
user#10.220.3.xx's password
After entering the password i don't get see anything not even 'Test Pgm'. How do i get the prompt remotely and input the values?
Try adding fflush(stdout); before the scanf().
Also, you must check the return value of scanf(), it can fail to convert the input if given non-numerical text:
fflush(stdout);
if(scanf("%d", &i) == 1)
printf("Number input: %d\n", i);