Sam Meow
Sam Meow

Reputation: 211

C++ int to string conversion

Current source code:

string itoa(int i)
{
    std::string s;
    std::stringstream out;
    out << i;
    s = out.str();
    return s;
}

class Gregorian
{
    public:
        string month;
        int day;
        int year;    //negative for BC, positive for AD


        // month day, year
        Gregorian(string newmonth, int newday, int newyear)
        {
            month = newmonth;
            day = newday;
            year = newyear;
        }

        string twoString()
        {
            return month + " " + itoa(day) + ", " + itoa(year);
        }

};

And in my main:

Gregorian date = new Gregorian("June", 5, 1991);
cout << date.twoString();

I'm getting this error:

mayan.cc: In function ‘int main(int, char**)’:
mayan.cc:109:51: error: conversion from ‘Gregorian*’ to non-scalar type ‘Gregorian’ requested

Does anyone know why int to string conversion is failing in here? I'm fairly new to C++ but am familiar with Java, I've spent a good deal of time looking for a straightforward answer to this problem but am currently stumped.

Upvotes: 5

Views: 6506

Answers (2)

dodo
dodo

Reputation: 43

You can use this function to convert int to string, after including sstream:

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

You are assigning a Gregorian pointer to a Gregorian. Drop the new:

Gregorian date("June", 5, 1991);

Upvotes: 15

Related Questions