简体   繁体   中英

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.

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

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM