What exactly getch() does in C? - c

I thought (upto now) that the function of getch() reads a character from input buffer (or keyboard, to be simple). But i had to argue with my lab instructor. They say that the only work of getch() is to hold the program execution. I know that getch() can be used that way. But i just wanted to know was it the real purpose it was invented? Or, Is it rarely used in getting one-character inputs?

getch is used to “read a single-byte character from the terminal associated with the current window” as specified by POSIX. That is its primary function. It can be configured to be non-blocking (e.g. the function returns straight away if there is no input) so your lab instructor would be wrong to say that its only purpose is to pause program execution.
If you're talking about the getch() implemented by Turbo-C then I'm not sure of the blocking semantics, but if its primary purpose was to pause program execution the function would surely be named something more apt, such as pause() or waitkb() or something similar.

Well as you know, getch() reads a single byte character from input.
In those great days of Turbo C compiler,
Common use of getch is that you can view the output (if any) of your
program without having to open the output window if you are using
turbo c compiler or if you are not running your program from command
prompt
Ah, those were days!!
BTW getch is said to be deprecated.

getch() is a way to get a user inputted character. It can be used to hold program execution, but the "holding" is simply a side-effect of its primary purpose, which is to wait until the user enters a character. They wouldn't have made getch() if holding program execution was its only purpose, since there are other ways to hold program execution. Also, keep in mind that getch() is not platform independent, so use at your own peril...

yes, getch() gets a character,it is correct , that means you have to give one input character,it is main work
but until you provide input character it waits, means until it return the value of the keypress
for getting character input ,you can use it anywhere in programme , but for to view the output of your program without having to open the output window( in Turbo C compiler) ,you can use it as last statement of your programme

There is a description of getch() here
It does return the value of the keypress as an int.

Related

What's the difference between putch() and putchar()?

Okay so, I'm pretty new to C.
I've been trying to figure out what exactly is the difference between putch() and putchar()?
I tried googling my answers but all I got was the same copy-pasted-like message that said:
putchar(): This function is used to print one character on the screen, and this may be any character from C character set (i.e it may be printable or non printable characters).
putch(): The putch() function is used to display all alphanumeric characters through the standard output device like monitor. this function display single character at a time.
As English isn't my first language I'm kinda lost. Are there non printable characters in C? If so, what are they? And why can't putch produce the same results?
I've tried googling the C character set and all of the alphanumeric characters there are, but as much as my testing went, there wasn't really anything that one function could print and the other couldn't.
Anyways, I'm kind of lost.
Could anyone help me out? thanks!
TLDR;
what can putchar() do that putch() can't? (or the opposite or something idk)
dunno, hoped there would be a visible difference between the two but can't seem to find it.
putchar() is a standard function, possibly implemented as a macro, defined in <stdio.h> to output a single byte to the standard output stream (stdout).
putch() is a non standard function available on some legacy systems, originally implemented on MS/DOS as a way to output characters to the screen directly, bypassing the standard streams buffering scheme. This function is mostly obsolete, don't use it.
Output via stdout to a terminal is line buffered by default on most systems, so as long as your output ends with a newline, it will appear on the screen without further delay. If you need output to be flushed in the absence of a newline, use fflush(stdout) to force the stream buffered contents to be written to the terminal.
putch replaces the newline character (\ n)
putchar is a function in the C programming language that writes a single character to the standard output

pause function in C does not respond to enter key

char keyin, buffer[1024];
do
{
keyin=gets(buffer);
}
while (keyin != "\n");
I have been trying to write a pause function in C where a user exits a paused state by pressing the Enter key. Where the user writes "pause" and this function gets executed. I have been working on this function for a while and it eludes me. I have implemented the code in several different ways and none of them work. I suspect it's because the comparison of "\n" with keyin. I think "\n" does not directly translate to the enter key.
You do not need a while loop to wait for a single Enter key press. It will wait (and you can press any key) until you press Enter: http://en.cppreference.com/w/c/io/gets
But you need to reserve a lot of space -- what if someone keeps pressing any other key "until something happens"? The buffer will overflow, and your program will (most likely) crash.
You probably want to use getchar -- this will send one keypress at a time back.
Note: the Enter key typically sends the ASCII code 13 (0x0D), not 10 (0x0A). You could use '\r' instead (minding others' notes on 'character' vs. "string"!), or prevent all confusion and use the hex or dec value.
This is different from the behavior of '\n' you are used to when outputting, because only certain functions will expand or convert the code '\n' in text to the required end-of-line sequence for your OS.
You cannot compare strings with == or != in C. You must compare the contents of the strings with a function like strcmp (or, preferably, one of the safer variants), e.g.:
while (strcmp(keyin, "\n") != 0);
As an aside, you should never ever actually use gets. It is impossible to use safely and securely.

Is it possible to capture Enter keypresses in C?

I want to write a C program that tokenizes a string and prints it out word by word, slowly, and I want it to simultaneously listen for the user pressing Enter, at which point they will be able to input data. Is this possible?
Update: see #modifiable-lvalue 's comment below for additional helpful information, e.g., using getchar() instead of getch(), if you go that route.
Definitely possible. Just be aware that gets() may not be entirely helpful for this purpose, since gets() interprets enter not as enter per se, but as "now, I the user, have entered as much string as I want to". So the input gathered by gets() from pressing just an enter will appear as an empty string (which might be workable for you).
See: http://www.cplusplus.com/reference/cstdio/gets/.
But there are other reasons not to use gets()--it does not let you specify a maximum to read in, so it's easy to overflow whatever buffer you are using. A security and bug nightmare waiting to happen. So you want fgets(), which allows you to specify a maximum size to read in. fgets() will place a newline in the string when an enter is pressed. (BTW, props to #jazzbassrob on fgets()).
You could also consider something like getch()--which really deals with individual key-presses (but it gets a bit complicated handling keys that have non-straightforward scan-codes). You may find this example helpful: http://www.daniweb.com/software-development/cpp/code/216732/reading-scan-codes-from-the-keyboard. But because of the scancodes issues, getch() is subject to platform details.
So if you want a more portable approach, you may need to use something heavier weight, but fairly portable, such as ncurses.
I suspect you can do what you want with either fgets(), keeping in mind that enter will give you a string with just a newline in it, or getch().
I just wanted you to be aware of some of the implementation/platform issues that can arise.
C can absolutely do this, but it's a little more complicated than one might guess at first attempt. That's because terminal input is, historically, very platform dependent.
Check out the conio.h library and its use in game making. You can compile with Borland. That was my first experience in unbuffered input and listening for keypresses in real time. There are certainly other ways though.

This program sounds the bell!

I'm a brand-new student in programming arena so I can't grasp this program written in my book that I have been following for a few days. The program is like this:
#include "stdio.h"
main()
{
printf("\a");
}
What does this program mean? Does this program mean that we could hear a ringing bell? I can't hear any ringing bell sound!!!
ASCII character 7 is the BELL character, and it's represented in C as \a. Some terminals will produce a beep when this character is output on the terminal; nowadays, many don't. (I'm looking at you, Ubuntu.)
Back in the dark ages when ASCII was codified out of the ashes of BAUDOT, a terminal was a large chunk of iron that hammered ink onto paper, often included a paper tape punch and reader, and interpreted keystrokes to generate an asynchronous serial signal at a few hundred baud with spinning wheels and relays.
In case an operator fell asleep to the soothing noises of it hammering out text, it had an actual bell it could ring. The character coded 007 in octal, 0x07 in hex, or as \a in a C character or string constant rang the bell when received.
As terminals became smaller and implemented with few or no moving parts, the physical bell was replaced by a beeper.
Exactly what your terminal emulator (aka a Console Window in Windows, xterm or something similar in Unix) does when it is asked to display that control character is not well standardized today. It ought to make a noise or flash the window, but your mileage will vary.
Have a look at this wikipedia entry: bell character:
In the C Programming Language (created in 1972), the bell character can be placed in a string or character constant with \a ('a' stands for "alert" or "audible" and was chosen because \b was already used for backspace).
\a does in fact trigger the system chime. It's the escape sequence for the ASCII BEL character.
You'll hear a beep from your PC's internal speaker (not the external speakers or headphones you may have attached).
Strings can contain characters which are handled different from all the other characters. The most often explicit used one is '\n'. The '\n' character does not print a character in the console, instead it tells the console to start a new line. Such special characters are called non printable since they have no own visible representation in c and have to use escape sequences instead.
In the escape sequence "\a" the backslash before the a tells the compiler that the a is an identifier for a special character and will store its char-value instead of the char-value of 'a'.
The '\a' escape sequence is the audible bell character, giving this character to a console via print() should cause a beep sound. Some consoles wont beep.
Here are some special characters, the link is from a c++ reference but most should be valid for c.
\a is the C representation of the ASCII audible alert ("bell") control character.
On an old-school serial terminal, outputting that character produced a "beep" sound. Your terminal emulator may or may not implement this feature.
Apart from all the answers you've got, take into account that your program won't probably compile. Here is the fixed version:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("\a");
return EXIT_SUCCESS;
}
The most important change is that system headers must be surronded with < and >, instead of quotes. Also, it is better to know that the main() function always returns an int (to the operating system), and that this int is coded in two constants, EXIT_SUCCESS, and EXIT_FAILURE, in the header stdlib.h
Try something simpler:
printf("hello\tworld");
printf("hello\nworld");
and see what happens.
Your example with the BELL char, as others have pointed out, probably won't work on today's toasters^H^H^H^H^H^H^H^H computers; most terminals redirect the 'bell' character to either be discarded or to flash the terminal briefly.
And believe me, you want to keep it that way for the night-coding sessions :)
The above program which you have written I have tried it in the code blocks using GNU GCC Compiler..
It was working fine..
If you want to hear a beep sound you can try it another way it will only be useful in Windows!
#include<stdio.h>
#include<windows.h>
main()
{
Beep(600,600); /* you have to enter both the values whatever you want
}
As a matter of interest this appears to work in all builds that don't have a wWinMain or WinMain entry point. wprintf(L"\a") sounds fine for Unicode builds. (Win 7 here).
The PC speaker used to depend on "speaker.drv" but that little beauty has been taken away some time back and replaced with beep.sys which is now moved into the user mode system sounds agent.
Enabling and disabling the speaker from the command prompt is also discussed here.
#include<stdio.h>
int main()
{
int i = 263;
putchar(i); // or you can directly use putchar(263);
return 0;
}
This program produces a bell sound while you are on the output screen
the problem isnt about wheter your C program compiles its fully depend your terminal settings usually they make beeps using PC speakers that comes with laptop and PCs before UEFI exist
https://en.wikipedia.org/wiki/PC_speaker
i tested it using 2 laptops one of them were bought before UEFI even a thing and other bought after UEFI become common thing
i run echo -e '\a' on both test (both linux system with pcspkr module loaded) and sure the laptop before UEFI exist is beep other laptop just silent

How to ignore arrow keys in C reading from stdin?

I'm reading from the standard input using the read() system call but there's a tiny thing that bothers me. I can't use the arrow keys... What I really wanted to do was to use arrow keys to go back and forth within the typed text but I think that's not that easy... So, what I at least want to do, is to ignore them.
Right now, pressing any of the arrow keys produces strange output and I want to prevent anything from being written to the standard output (consequently read from the standard input in my read() system call).
Is this easily possible to achieve or it's not that easy?
In order to interpret the arrow keys the way you would ideally like to (i.e. to move back and forth and edit the input), you generally need to use a library. For Linux, the standard is GNU Readline. Hopefully someone else can say what you would normally use for a Windows CLI app.
The answer ultimately depends on where the keys come from. I ran this program under Cygwin:
int main(void)
{
int c=0;
while( c != 'X' ) {
c = getchar();
printf("\nc=%d", c);
}
}
Every time a cursor key comes along, I see escape (27), a bracket, plus another character.
So, if you get results like that, you can skip 3 keys every time you see a 27. You could also look at them and make use of them!
As mentioned, YMMV, especially for the O.S., and the actual key-getting function you call.

Resources