Which of the following is the correct syntax to read a single character from…
2023
Which of the following is the correct syntax to read a single character from the console in C++?
Answer: C. get(ch) — ConceptIn C++, single-character input is performed through an input stream. The member function get(char&) extracts one character and stores it in the…
- A.
read ch() - B.
getlinech() - C.
get(ch) - D.
More than one of the above - E.
None of the above
Attempted by 549 students.
Show answer & explanation
Correct answer: C
Concept
In C++, single-character input is performed through an input stream. The member function get(char&) extracts one character and stores it in the supplied char variable; unlike formatted extraction with operator>>, it can also read whitespace.
Application
Let
char ch;be the destination variable.The complete standard-library call is
std::cin.get(ch);.The official source paper writes this member-call syntax in the shortened form
get(ch), withchas the argument.
Contrast
The form
read ch()separatesreadfrom the callch(); it is not the input-stream member-call form.The form
getlinech()names a different, non-standard identifier;std::getlineis instead used to read a sequence such as a line.The form
get(ch)represents the intended one-argument member-function call, written fully asstd::cin.get(ch).“More than one of the above” would require at least two listed syntaxes to represent the intended operation.
“None of the above” would require the intended form to be absent from the list.
Cross-check
With input consisting of a leading space followed by A, std::cin.get(ch) first stores the space in ch. This confirms that get consumes exactly one character, including whitespace.
Result
Therefore, the source-paper form is get(ch).