【问题标题】:How to add a number to an integer like a string如何将数字添加到整数(如字符串)
【发布时间】:2015-11-21 03:16:25
【问题描述】:

在 C++ 中,我试图将两个整数相加。我不想要这个:

5 + 5 = 10

我希望它是:

5 + 5 = 55

如何像字符串一样将两个整数相加。我知道怎么做,但是代码会很多,我只是想知道是否有四行以下的简短版本。

编辑:由于 Mingw 不能正确支持某些 C++11 功能,例如 to_string()、itoa(),因此我正在寻找不使用 C++11 功能的东西。

【问题讨论】:

  • std::to_string(5) + std::to_string(5) ?
  • Mingw 不支持 to_string 等 C++11 特性。
  • 您应该在问题中说明这一点。感谢std::stringstreamto_string 可以实现。

标签: c++ integer


【解决方案1】:

如果您想要 int 作为结果,请乘以底数:

int a = 5;
int b = 5;
int c = 10 * a + b;  // 55

如果您希望结果为std::string,请使用std::to_string(C++11 起):

int a = 5;
int b = 5;
std::string c = std::to_string(a) + std::to_string(b);  // "55"

在 C++11 之前,您可以使用 std::stringstream:

int a = 5;
int b = 5;
std::stringstream ss;
ss << a << b;
std::string c = ss.str();  // "55"

【讨论】:

  • 有没有其他更简单的方法不使用 C++11 功能,因为我使用的是 Mingw,它有错误,或者它只是不支持 C++11 功能所以我不能使用 to_string。
  • @Hydra 在 C++11 之前,您将使用 std::stringstream。我在答案中添加了一个示例。
  • 谢谢您,很抱歉没有在我的问题中添加该内容。您的示例完美运行,我已经实施并接受了您的回答!
【解决方案2】:

试试这个:

  #include<iostream>
  using namespace std;

  int main(){

 int value1 = 5;
 int value2 = 4;

  string put_together = to_string(value1) + to_string(value2);

  return 0 ;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多