Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Sam Meow Avatar asked Apr 23 '12 20:04

Sam Meow


People also ask

Can you turn an int into a string in C?

itoa() Function to Convert an Integer to a String in C itoa() is a type casting function in C. This function converts an integer to a null-terminated string.

How can a number be converted to a string in C?

Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf().

How do you convert integers to strings?

The easiest way to convert int to String is very simple. Just add to int or Integer an empty string "" and you'll get your int as a String. It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String.

What is strtol () in C?

In the C Programming Language, the strtol function converts a string to a long integer. The strtol function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.


1 Answers

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

Gregorian date("June", 5, 1991);
like image 183
juanchopanza Avatar answered Sep 23 '22 00:09

juanchopanza