LearnFrenzy
Sign in Take a free test

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

Building a string with ostringstream and manipulators Answer, explanation & discussion

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

What is the output of the following C++ program?

main.cpp
#include <iomanip>
#include <iostream>
#include <sstream>

int main() {
    std::ostringstream out;
    out << "ID-" << std::setw(4) << std::setfill('0') << 37 << '/' << std::fixed << std::setprecision(1) << 9.25;
    std::string s = out.str();
    std::cout << s << ' ' << s.size() << '\n';
    return 0;
}
  • A ID-0037/9.2 11 Correct
  • B ID-37/9.3 9
  • C ID-0037/9.3 11
  • D ID-0037/9.25 12
Correct Answer: Option A

37 is zero-padded to 4 digits. 9.25 is exactly representable, so with one decimal it is a tie that rounds to even: 9.2. The string has 11 characters.

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