Which inbuilt function in C is used to read string from system console?
2021
Which inbuilt function in C is used to read string from system console?
Answer: B. cgets () — ConceptEvery C console routine is fixed by two independent properties: its direction — whether the call moves characters from the keyboard into the program or…
- A.
puts ()
- B.
cgets ()
- C.
getche ()
- D.
getchar ()
Attempted by 2364 students.
Show answer & explanation
Correct answer: B
Concept
Every C console routine is fixed by two independent properties: its direction — whether the call moves characters from the keyboard into the program or from the program out to the display — and its granularity — whether one call handles a single character or a whole line of characters held in a buffer. A routine is the right tool only when both properties match the task; being an input call does not make a routine string-capable, and handling strings does not make a routine an input call.
Applying the concept here
The stem fixes both properties. "Read" fixes the direction as input, and "string" fixes the granularity as a whole line into a character buffer. So the routine being asked for is a console-input call that fills a character array in one go.
The four candidates side by side
Function | Header | Direction | Unit per call |
|---|---|---|---|
|
| output | a whole string |
|
| input | a whole line into a buffer |
|
| input | one character |
|
| input | one character |
The two single-character routines differ only in where the character comes from: getche() takes the keystroke directly from the console and echoes it at once, while getchar() pulls the next character from the buffered standard input stream and returns it as an int, signalling end of input with EOF.
Result
Only one candidate carries both required properties — input direction and whole-line granularity — and that is cgets(). It is handed a character buffer whose first byte has been preset to the maximum length; it stores the line typed at the console from the third byte onward and writes the number of characters actually read into the second byte. It is therefore the inbuilt function that reads a string from the system console among those offered.
Cross-check and a caution
Substitute each candidate into a task that must capture a typed name into char buf[82]: puts(buf) would print the array instead of filling it, and getche() or getchar() would capture a single keystroke, so the array would need a loop to be filled. Only cgets(buf) fills it in one call.
Caution: cgets() is a Turbo-C / DOS extension supplied by <conio.h>; it is not part of ISO standard C and is unavailable in modern portable compilers. In present-day C the safe way to read a line is fgets(buf, sizeof buf, stdin) (and gets() was removed from the language in C11 because it cannot bound the input). For this DSSSB question, the intended classical answer is the console string-reading routine cgets().