LearnFrenzy
Sign in Take a free test

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

Reading letters into an int: value and fail state Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

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

main.cpp
#include <iostream>
#include <string>

int main() {
    int x = 7;
    std::cin >> x;
    std::cout << x << ' ' << std::cin.fail() << ' ';
    std::string rest;
    std::cin >> rest;
    std::cout << '[' << rest << "]\n";
    return 0;
}
  • A 0 1 [] Correct
  • B 7 1 [abc]
  • C 0 1 [abc]
  • D 7 0 []
Correct Answer: Option A

The failed extraction sets x to 0 (C++11) and failbit. Without clear(), the next read into rest fails too and leaves it empty – "abc" is still waiting in the buffer.

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