Notepad++ and NppExe not showing me an output - c

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.

Related

How to use printf() and scanf() in C without going to the next line?

I want to get date of birth in one line:
#include <stdio.h>
int main()
{
int BirthYear,BirthMonth,BirthDay;
printf("Please enter your birth date: ");
scanf("%d",&BirthYear);
printf("/");
scanf("%d",&BirthMonth);
printf("/");
scanf("%d",&BirthDay);
return 0;
}
This is my output:
Please enter your birth date: YYYY
/MM
/DD
But I want to get something like this:
Please enter your birth date: YYYY/MM/DD
In output, it goes to next line after each scanf() without using \n.
I use VS Code for IDM.
Here is a workaround using ansi control characters. I would not do like this, but just to show that it is possible:
#define PREVLINE "\033[F"
#define MSG "Please enter your birth date: "
int main(void) {
int BirthYear,BirthMonth,BirthDay;
printf(MSG);
scanf("%d",&BirthYear);
printf(PREVLINE MSG "%d/", BirthYear);
scanf("%d",&BirthMonth);
printf(PREVLINE MSG "%d/%d/", BirthYear, BirthMonth);
scanf("%d",&BirthDay);
printf("You entered: %d/%d/%d\n", BirthYear, BirthMonth, BirthDay);
}
Please note that this is not portable. The terminal needs to support this in order to work. AFAIK there's no 100% portable way to achieve this.
If you want to do this stuff for real, then I recommend taking a look at the ncurses library
Note:
Always check the return value for scanf to detect errors.
Note2:
It may be a good idea to add fflush(stdout); after each printf statement.
I actually wrote another answer today about ascii control characters. It might be interesting: https://stackoverflow.com/a/64549313/6699433
You can explicitly specify that the three input numbers should be separated by a '/' character by adding that character in the format specifier for the scanf function.
Then, you can ensure that the user gave valid input by checking the value returned by scanf (which will be the number of items successfully scanned and assigned); if that value is not 3, then you will (probably) need to clear any 'leftover' characters in the input buffer, using a getchar() loop until a newline (or end-of-file) is found:
#include <stdio.h>
int main()
{
int BirthYear, BirthMonth, BirthDay;
int nIns = 0, ch;
while (nIns != 3) {
printf("Enter D.O.B. (as YYYY/MM/DD): ");
nIns = scanf("%d/%d/%d", &BirthYear, &BirthMonth, &BirthDay);
while ((ch = getchar() != '\n') && (ch != EOF))
; // Clear remaining in-buffer on error
}
printf("Entered data were: %d %d %d!\n", BirthYear, BirthMonth, BirthDay);
return 0;
}
Expanding on my comment...
The problem you're running into is that you have to hit Enter for each input, which writes a newline to the terminal screen. You can't avoid that.
And unfortunately, you can't overwrite the newline on the screen with a '\b'; you can only backspace up to the beginning of the current line, not to a previous line.
You basically can't do what you want with vanilla C - the language only sees byte streams, it has no concept of a "screen".
There are some terminal control sequences you can play with to reposition the cursor after sending the newline; I don't know how well those will work for you.
Beyond that, you'll need to use a library like ncurses.
#include <stdio.h>
int main()
{
int BirthYear,BirthMonth,BirthDay;
printf("Please enter your birth date: ");
scanf("%d/%d/%d",&BirthYear,&BirthMonth,&BirthDay);
return 0;
}
You can take multiple values from scanf which are then separated by any text you like (in this case /s).
You could use fflush(3) (in particular before all calls to scanf(3)) like in
printf("Please enter your birth date: ");
fflush(NULL);
but you should read this C reference website, a good book about C programming such as Modern C, and the documentation of your C compiler (perhaps GCC) and debugger (perhaps GDB).
Consider enabling all warnings and debug info in your compiler. With gcc that means compiling with gcc -Wall -Wextra -g
Be aware that scanf(3) can fail.
Your code and problem is surely operating system specific.
On Linux consider using ncurses (for a terminal interface) or GTK (for a graphical interface). Read also the tty demystified, then Advanced Linux Programming and syscalls(2) and termios(3).
You might also consider using ANSI escape codes, but be aware that in 2020 UTF-8 should be used everywhere.

C Scanf Command Won't Run

I am a new learner to the C language. I am trying to figure out how to use scanf. This is my code so far.
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
scanf(" %c", &lastInitial);
}
When I run this code (I'm using VS Code), it shows that the file is running, but nothing shows up. When I go to the top to click the run button again, it says this code is already running. If I stop the run, delete the scanf line and run again, the file runs and displays "What is your last inital?" I am confused as to why adding scanf to the file stops the printf and doesn't allow any user input.
You might have run into a little intricacy with how printf works. When you run printf("What is your last inital?");, this text does not end with a newline (\n) character. As a result, some environments might not display it right away, delaying it until you printf a complete line or until the program ends. This is done for efficiency, since the internal steps to actually get output to your screen are a bit expensive.
When you remove the scanf, the program ends right after the printf; as the program is ending any text that's still waiting to be displayed gets sent to the screen by the built-in shutdown routines in the C standard library. However, when the scanf is included, the text gets buffered/delayed, and doesn't ever get sent to the screen sine the program is stalled waiting for user input. You can force the output to be sent immediately using a newline:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?\n");
scanf(" %c", &lastInitial);
}
Or if you don't want a newline, you can tell the C standard library to explicitly send all output text right away:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
fflush(stdout);
scanf(" %c", &lastInitial);
}
When you run the program, you should switch from "OUTPUT" to "TERMINAL".
You need to install the "Code Runner" extension.
Then go to File-->Preferences-->Settings in the search write code runner, and below will appear some settings of code runner, you need to find Run In Terminal, and turn it on.
THAT'S ALL :)

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;
}
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.

Why my little C game ignore player's first attempt? [duplicate]

This question already has answers here:
Why doesn't getchar() wait for me to press enter after scanf()?
(10 answers)
Closed 3 years ago.
I'm learning programmation in C and tried to create a program that asks the user his age. When the user writes his age (for example 18) he gets the message "So you're 18 years old". When I execute the .exe file it automatically closes after you see the message, so fast that you don't see it. Then I added getchar so that the user reads the message and then presses Enter to quite. Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age=0;
printf("How old are you?\n");
scanf("%d",&age);
printf("So you're %d years old", age);
getchar();
return 0;
}
Unfortunately, when I execute the .exe file, it still closes automatically like if the getchar() doesn't exist and I don't know why.
scanf("%d",&age);
When the execution of the program reaches the above line,you type an integer and press enter.
The integer is taken up by scanf and the \n( newline character or Enter )which you have pressed remains in the stdin which is taken up by the getchar().To get rid of it,replace your scanf with
scanf("%d%*c",&age);
The %*c tells scanf to scan a character and then discard it.In your case,%*c reads the newline character and discards it.
Another way would be to flush the stdin by using the following after the scanf in your code:
while ( (c = getchar()) != '\n' && c != EOF );
Note that c is an int in the above line
You're only having trouble seeing the result because you're starting the program from a windowing environment, and the window closes as soon as its internal tasks are completed. If you run the compiled program from a command line in a pre-existing shell window (Linux, Mac, or Windows), the results will stay on the screen after you're returned to the prompt (unless you've ended by executing a clear-screen of some sort). Even better, in that case, you don't need the extraneous getchar() call.
For Windows, after opening the command prompt window, you'd issue a "cd" command to change to the directory that contains the compiled program, and then type its name. For Linux (and, I presume, Mac, since Mac is UNIX under the hood), you'd need to type ./ ahead of the program name after changing to the appropriate directory with "cd".

getchar not taken in consideration after scanf [duplicate]

This question already has answers here:
Why doesn't getchar() wait for me to press enter after scanf()?
(10 answers)
Closed 3 years ago.
I'm learning programmation in C and tried to create a program that asks the user his age. When the user writes his age (for example 18) he gets the message "So you're 18 years old". When I execute the .exe file it automatically closes after you see the message, so fast that you don't see it. Then I added getchar so that the user reads the message and then presses Enter to quite. Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age=0;
printf("How old are you?\n");
scanf("%d",&age);
printf("So you're %d years old", age);
getchar();
return 0;
}
Unfortunately, when I execute the .exe file, it still closes automatically like if the getchar() doesn't exist and I don't know why.
scanf("%d",&age);
When the execution of the program reaches the above line,you type an integer and press enter.
The integer is taken up by scanf and the \n( newline character or Enter )which you have pressed remains in the stdin which is taken up by the getchar().To get rid of it,replace your scanf with
scanf("%d%*c",&age);
The %*c tells scanf to scan a character and then discard it.In your case,%*c reads the newline character and discards it.
Another way would be to flush the stdin by using the following after the scanf in your code:
while ( (c = getchar()) != '\n' && c != EOF );
Note that c is an int in the above line
You're only having trouble seeing the result because you're starting the program from a windowing environment, and the window closes as soon as its internal tasks are completed. If you run the compiled program from a command line in a pre-existing shell window (Linux, Mac, or Windows), the results will stay on the screen after you're returned to the prompt (unless you've ended by executing a clear-screen of some sort). Even better, in that case, you don't need the extraneous getchar() call.
For Windows, after opening the command prompt window, you'd issue a "cd" command to change to the directory that contains the compiled program, and then type its name. For Linux (and, I presume, Mac, since Mac is UNIX under the hood), you'd need to type ./ ahead of the program name after changing to the appropriate directory with "cd".

Resources