LearnFrenzy
Sign in Take a free test

std::string · Predict the Output · Question 16

Splitting with getline keeps empty fields 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 on a 64-bit system?

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

int main() {
    std::istringstream in("a;;b;c;");
    std::string part;
    int n = 0;
    while (std::getline(in, part, ';')) {
        std::cout << '<' << part << '>';
        ++n;
    }
    std::cout << ' ' << n << '\n';
    return 0;
}
  • A <a><><b><c> 4 Correct
  • B <a><b><c> 3
  • C <a><><b><c><> 5
  • D <a;;b;c;> 1
Correct Answer: Option A

The empty field between ;; is returned, but a trailing delimiter does not produce a final empty field: getline fails when nothing follows it.

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