Application files made using CodeBlocks won't run outside the IDE - c

I've been learning programming with C and have made some starter programs using CodeBlocks. The problem is that I can't run the application files that are saved in bin\debug by double right clicking on them. Instead, I have to open the project file and hit "Run" or "Build and Run" to do so. Is there a way to fix this?

Firstly, "double click" means "double (left) click" and not "double (right) click".
Even if your machine does support "double right click" to open a file, the following could be a problem.
Consider a small program like this:
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
You can see its results when you run it inside the IDE because it waits for you to "press any key" before terminating it.
But when you run it outside the IDE, the program is terminated immediately at the end of main. The program will open, execute, and terminate before even you realizing it. It happens very quickly. In case of programs dealing with user inputs, you can see the intermediate results though.
Solution:
An easy fix is to add getchar() to the end of main. It will wait for you to press the enter key in order to quit the console application.
#include <stdio.h>
int main()
{
printf("Hello World");
getchar(); // <-- add this line of code
return 0;
}
You can also have a more controlled termination by making your own exit function.
For example, if your program leaves a newline in the buffer before calling the getchar, it would consume the '\n' and not wait for you to press the enter key. In that case, you should clear the input buffer:
// clear the input buffer
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
// then call getchar
getchar();

Related

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 :)

Character Counter from "The C Programming Language" Not Working As I Expected

I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this:
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
When I run the program, it opens a window I can type in, but when I hit enter all that happens is it skips down a line and I can keep typing, but I think it's supposed to print the number of characters.
Any idea what's going wrong?
This line:
while (getchar() != EOF)
means that it keeps reading until the end of input — not until the end of a line. (EOF is a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.
If you want to terminate on EOL (end of line), replace EOF with '\n':
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != '\n')
++nc;
printf("%ld\n", nc);
}
Enter is not EOF. Depending on your OS, Ctrl-D or Ctrl-Z should act as EOF on standard input.
I ran into the problem tonight, too. Finally found out that Ctrl-D on Linux worked. You build the source file using cc, and start the program and input a word, then press Ctrl-D twice when finished typing. The number that the program countered will be printed just behind the very word you just typed, and the program terminates immediately. Just like this:
The above answer provided by nujabse is correct. But recently coming across this issue myself and researching the answer, I would like to add why.
Using Ctrl+C tells the terminal to send a SIGINT to the current foreground process, which by default translates into terminating the application.
Ctrl+D tells the terminal that it should register a EOF on standard input, which bash interprets as a desire to exit.
What's the difference between ^C and ^D

Capturing a user's "enter" keystroke in C

I'm starting to learn C now and i'm trying to figure out how I would go about capturing when the user hits "enter." I'm looking particularly at the scanf and getc functions but I'm not quite sure how to go about it. When the user hits enter I want to perform some operations while waiting/watching for him to hit enter again... Is "enter" a new line character coming in from the console? Any advice would be much appreciated!
You can check the ascii value using fgetc().
while(condition) {
int c = fgetc(stdin);
if (c==10) {//Enter key is pressed
//your action
}
}
If you just need the input when user presses enter as input you can use scanf or getchar. Here is an example from cplusplus.com
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
This code prints what you entered to stdin (terminal window).
But if you do not want the input ( i know it's really unnecessary and complicated for a new learner) you should use an event handler.
printf("Hit RETURN to exit"\n");
fflush(stdout);
(void)getchar();
Ref: comp.lang.c FAQ list · Question 19.4b
The C language is platform-independent and does not come with any keyboard interaction on its own. As you are writing a console program, it is the console that processes the keyboard input, then passes it to your program as a standard input. The console input/output is usually buffered, so you are not able to react to a single keypress, as the console only sends the input to the program after each line.
However! If you do not demand your console application to be platform-independent, there is a non-standard library <conio.h> in some Windows compilers that has a function called getche();, which does exactly what you want - wait for a single keypress from the console, returning the char that was pressed.

Confused about getchar() function

I am confused about getchar()'s role in the following code. I mean I know it's helping me see the output window which will only be closed when I press the Enter key.
So getchar() is basically waiting for me to press enter and then reads a single character.
What is that single character this function is reading? I did not press any key from the keyboard for it to read.
Now when it's not reading anything, why does it not give an error saying "hey, you didn't enter anything for me to read"?
#include <stdio.h>
int main()
{
printf( "blah \n" );
getchar();
return 0;
}
That's because getchar() is a blocking function.
You should read about blocking functions, which basically make the process wait for something to happen.
The implementation of this waiting behavior depends on the function, but usually it's a loop that waits for some event to happen.
For the case of the getchar() function, this probably is implemented as a loop that constantly reads a file (stdin for this case) and checks weather the file is modified. If the file is modified, the loop behaves by doing something else.
The getchar() function will simply wait until it receives a character, holding the program up until it does.
A character is sent when you hit the enter key; under a Windows OS, it will send a carriage return (CR) and a line-feed (LF).
See this CodingHorror post for a nicely put explanation.
(...the explanation of the CR+LF part, not the getchar() blocking part)
Try this:
#include <stdio.h>
int main(int argc, char *argv[])
{
char ch;
printf("I'm now going to block until you press something and then return... ");
ch = getchar();
if (ch >= 0)
printf("\nYou pressed %c\n", ch);
else
printf("\nAliens have taken over standard input! Run!\n");
return 0;
}
getchar() will cause your program to go to sleep until a keyboard (or whatever is attached to stdin) interrupt is received. This means it's blocking, no additional code will execute until getchar() returns.
It's very, very helpful to look at the return value of a function in order to understand it.
Any function may block, unless it provides some mechanism to prevent blocking. For instance, open() allows a O_NONBLOCK flag which is helpful for opening slow to respond devices like modems. In short, if it gets input from a terminal or has to wait to get an answer from the kernel or some device, there's a very good chance it might block.
getchar() blocks your program's execution until a key is pressed. So, there's no error if no key is pressed, getchar() will wait for it to happen :)
You can learn more about how getchar behaves here:
http://www.cppreference.com/wiki/c/io/getchar
...this should answer your question:)
I think what confuses you is that the Enter key is needed befor the program continues. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.
see discussion of Enter problem here

Is there a way to get text as soon as possible without waiting for a newline?

I'm using C. I wrote a very simpe program which prints back the input, using getchar() and putchar() or printf(). Is there any way to make it so as soon as the user types one key, the program registers it, without waiting for an Enter? Let me show:
Currently, if the user types "abc" and then presses Enter, the program prints "abc" and a newline and keeps waiting for more input. I want to make it so as soon as the user types "a", the program prints "a" and waits for more input. I'm not sure whether this has to be done inside the source code or if something has to be changed in the Windows command line.
Just in case, here's the source code:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
if you are using Visual Studio, there is a library called conio (#include <conio.h>) which defines a kbhit() function and getch().
otherwise, on Windows, there is still the possibility of using functions from the Windows SDK (ReadConsoleInput() and the like), but that would require a little bit more code (although, once done and if done properly, it can be reused any time you want)
If you're using Visual Studio, you can use getch().
In this simple case, the other answers should suit you fine.
The general solution is to disable line buffering. This depends on the particular console; the following example is Windows-only (untested):
#include <windows.h>
int main() {
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hConsole, &mode);
SetConsoleMode(hConsole, mode & ~ENABLE_LINE_INPUT);
// ...
}
I assume that the standard C library functions are implemented in terms of ReadConsole and friends; if not, this might not even work. (I'm currently on Linux, so I cannot test this.)
On Linux you can take over the terminal:
#include <stdio.h>
#include <ctype.h>
#include <termios.h>
system("stty raw"); /* raw output to terminal, direct feedback */
system("clear"); /* clear screen */
printf("Press a key");
answer = getchar();
system("stty cooked"); /* revert back*/

Resources