Experts I've doubts in gets(),puts() and getch().
- Why do we use gets() and puts() when we have scanf() and printf()?
- What is the use of getch().
Please explain this in simple language because I'm a beginner.
THank you in advance. :)
Experts I've doubts in gets(),puts() and getch().
Please explain this in simple language because I'm a beginner.
THank you in advance. :)
gets
doesn't exist anymore (except in outdated environnments such as the infamous TurboC), use fgets
instead.
fgets
reads one line of text from a file including from the terminal (standard output)puts
writes one line of text to the terminal (standard output)fputs
writes one line of text to a file, including the terminal (standard output)getch
reads on character from the standard input (terminal)printf
and friends allow you to print formatted outputscanf
and friends allow you to read formatted input.Why do we use gets() and puts() when we have scanf() and printf()?
We don't use gets()
, the function was so poorly designed that it was flagged obsolete 18 years ago and finally completely removed from the C language 6 years ago. If someone taught you to use gets()
, you need to find a more updated source of learning. See What are the C functions from the standard library that must / should be avoided?.
puts(str)
is only used as a micro-optimization of printf("%s", str)
. puts()
is traditionally ever so slightly faster than printf()
, since it doesn't need to parse a format string. Today, this performance benefit is a non-issue.
However, puts()
is much safer than printf()
. You can write bad code like printf("%s", pointer_to_int)
and it might compile without warnings. But puts(pointer_to_int)
will never compile without warnings/errors.
Generally, most of stdio.h is dangerous and unsafe because of the poor type safety. It is avoided in professional, production-quality code. For student/hobbyist purposes, printf/scanf are however fine.
What is the use of getch()
getch()
was a non-standard extension to C, which allowed programs to read a character from stdin without echoing the typed character to stdout (the screen).
This function was popular back in the days of MS DOS when Borland Turbo C was the dominant compiler. Because Turbo C had it, some other compilers also started supporting it together with the non-standard conio.h
library. We're talking early 1990s.
You shouldn't use this function in modern C programming.
(Though it is possible to implement it yourself with various API calls, as in this example for Windows.)