What will be the output of the following C++ code using substr()?

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s = "COMPUTER";
    cout << s.substr(2, 3);
    return 0;
}
                        

Options

  • A. COM
  • B. MPU
  • C. PUT
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. MPU

Detailed Explanation

Correct Answer: Option B — MPU

Explanation: substr(pos, count) returns a substring starting at index pos and containing up to count characters. Starting at index 2 in COMPUTER gives M, and the next three characters are MPU.