LearnFrenzy
Sign in Take a free test

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

getline with std::ws after cin >> Answer, explanation & discussion

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

What is the output of the following C++ program when the input is 25⏎ Asha Rao⏎?

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

int main() {
    int age;
    std::string name;
    std::cin >> age;
    std::getline(std::cin >> std::ws, name);
    std::cout << age << " [" << name << "] " << name.size() << '\n';
    return 0;
}
  • A 25 [Asha Rao] 8 Correct
  • B 25 [ Asha Rao] 11
  • C 25 [] 0
  • D 25 [Asha] 4
Correct Answer: Option A

std::ws skips the newline and the leading spaces, then getline reads the rest of the line. Spaces inside the name are kept.

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