LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Predict the Output · Question 20

peek and putback while parsing input Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What is the output of the following C++ program when the input is x42?

main.cpp
#include <iostream>

int main() {
    char first = static_cast<char>(std::cin.peek());
    char c;
    std::cin.get(c);
    std::cin.putback(c);
    char again;
    std::cin >> again;
    int n;
    std::cin >> n;
    std::cout << first << c << again << ' ' << n + 1 << '\n';
    return 0;
}
  • A xxx 43 Correct
  • B x4x 42
  • C xx4 3
  • D xxx 42
Correct Answer: Option A

peek looks at x without removing it; get removes it; putback returns it, so >> reads x again. The number 42 is then read, and 42 + 1 is printed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links