Write a program that displays a subject summary

closed account (9G3v5Di1)
Write a program that displays a subject summary. Use an object to get the summary of the subject.

I'm not actually asking for codes. This is the header.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  //subject.h
#include <string>
#include <sstream>

using namespace std;

class Subject{
  private:
    string mTitle, mCode;
    short mUnits;

  public:
    Subject(string title, string code, short units){
      mTitle = title;
      mCode = code;
      mUnits = units;
    }

    string getSubjects() {
      ostringstream s;
        s << "[" << mCode << "] " << mTitle;
        s << "(" << mUnits << " units)";
        return s.str();
    }
};


What I don't understand is from line 20 to 23, the use of ostringstream s;, is that the same as cout, but in string form? Also line 23 uses s.str(), why not just s? Sorry for asking for an explanation as the module that I am reading did just use it without explaining further.
Hello goldwinbryanr,

When I look at the code:

First do not put "#include" files in a header file. These are for files with a '.cpp" extension. If the program is done correctly they are not needed.

Second NEVER put line 5 in a header file. Read this:
http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

"ostringstream" is like using an external file stream, but it is done with internal memory in the program. and yes it is like a "cout", but to memory not the screen.

The "s.str()" simply makes the "ostringstream" a regular stream.

These should explain things better.

http://www.cplusplus.com/reference/sstream/ostringstream/
http://www.cplusplus.com/reference/sstream/ostringstream/str/

Hope that helps,

Andy
Hello goldwinbryanr,

Sorry an after thought.

You can put the whole function in public, but it is better to put the proto types in the header file and put the whole function in a ".cpp" file usually withe the same file name as the header, but with a ".cpp" extension.

"mTitle" is OK, but more often I have seen this written as "m_Title" for these type of variables. Either way the "m" says that it is a member variable of a class.

Andy
See: https://www.artima.com/cppsource/streamstringsP.html

The member function getSubjects() should be const-qualified.
std::string getSubjects() const {
See: 'const member functions' https://docs.microsoft.com/en-us/cpp/cpp/const-cpp?view=vs-2017
Topic archived. No new replies allowed.