C ++ int到字符串转换

时间:2012-04-23 20:00:55

标签: c++ string int type-conversion

当前源代码:

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

};

在我的主要内容中:

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

我收到了这个错误:

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

有谁知道为什么int到字符串转换失败了?我对C ++很新,但是熟悉Java,我花了很多时间寻找这个问题的简单答案,但目前我很难过。

2 个答案:

答案 0 :(得分:15)

您正在为Gregorian分配Gregorian指针。放下new

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

答案 1 :(得分:0)

在包含sstream之后,您可以使用此函数将int转换为字符串:

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}
相关问题