【问题标题】:C++ int to string conversionC++ int 到字符串的转换
【发布时间】:2012-05-04 11:15:17
【问题描述】:

当前源代码:

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 很熟悉,我花了很多时间寻找这个问题的直接答案,但目前很难过。

【问题讨论】:

  • 您可以在 itoa 中删除 std::string s;,而只删除 return out.str();。返回字符串将在 stringstream 被销毁之前构造。合理的编译器可能会在这两种情况下生成完全相同的代码,但额外的临时代码往往会向查看您的代码的人暗示您不理解或不信任 C++ 范围规则。
  • 不相关,但您的意思是将函数命名为toString()
  • 来自 Java,我不知道 C++ 是否已经有了 toString() 方法。如果不需要,我不想超载它。

标签: c++ string int type-conversion


【解决方案1】:

你可以使用这个函数将 int 转换为 string,在包含 sstream 之后:

#include <sstream>

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

【讨论】:

  • 这没有回答问题。
【解决方案2】:

您正在将 Gregorian 指针分配给 Gregorian。删除new

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

【讨论】:

  • 哇,这是一个令人难以置信的快速响应。非常感谢您提供如此简单的解决方案。
  • @SamMeow 没问题。如果答案是可以的,那么您可以选择它。
猜你喜欢
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多