Oria Gruber
Oria Gruber

Reputation: 1533

Simple one line class method returning wrong value

I am having a weird issue and I don't know what's wrong.

I have a class publication composed of the class members string headline and string text.

I also have a class called publication_and_date which inherits from publication, but also has an additional field called string date which represents the date a certain article was published.

I also have a class news that inherits from publication_and_date, and has the additional field of string sources

The problem is this: I have an object of type news, and when i use the method get_date of that object, I get the value M.

Here is my void main:

void main()
{
    news MyNews;

    MyNews.set_date(3,12,2016);
    MyNews.set_sources("IGN");
    MyNews.set_headline("MGS V wins GOTY award");
    MyNews.set_text("Metal Gear Solid V won the prestigious game of the year award!");

    cout << MyNews.ToString();
    getch();
}

This is the implementation of the class publication_and_date:

publication_and_date::publication_and_date() : publication()
{
    date="1/9/2015";
}

void publication_and_date::set_date(const int NewDay,const int NewMonth,const int NewYear)
{
    if((NewDay > 31)||(NewDay < 1)||(NewMonth > 12)||(NewMonth < 1)||(NewYear<2015)) //input check
    {
        cout << "\nDate is invalid\n";
        return;
    }
    date=NewDay + '/' + NewMonth + '/' + NewYear;
}

string publication_and_date::get_date()
{
    return date;
}

As you can see, the method get_date() is very simple. It's just one line.

I don't know why the value I'm getting is M.

The output of the void main I gave you is:

Headline: MGS V wins GOTY award
Text: Metal Gear Solid V won the prestigious game of the year award!
Date: M
Sources: IGN

I'm completely baffled as to why this happens. Would appreciate help.

Edit1: This is the code for ToString

string news::ToString()
{
    string ToReturn;
    ToReturn="\nHeadline: " + get_headline() + '\n' + "Text: " + get_text() + '\n'+"Date: " + get_date()+'\n'+"Sources: " + get_sources();
    return ToReturn;
}

Edit2:

I think I know what the problem is. NewDay, NewMonth,NewYear are integers. So the + operator is not the same as with strings. I need to somehow make them chars.

Upvotes: 2

Views: 76

Answers (1)

Maksim Solovjov
Maksim Solovjov

Reputation: 3157

You are getting an M or something else random because you add up the numbers rather than concatenate strings. A char '/' is actually a small integer with the value of 47.

One way to convert everything into a string is to use a stringstream (located in sstream header):

std::stringstream ss;
ss << NewDay << '/' << NewMonth << '/' << NewYear;
date = ss.str();

A string stream is just like your regular iostream, but it works on strings. It will do the right thing with regards of type conversions.

Upvotes: 2

Related Questions