【问题标题】:how do you quickly concatenate an integer simmilar to concatenating strings [duplicate]你如何快速连接一个类似于连接字符串的整数[重复]
【发布时间】:2013-07-28 06:09:05
【问题描述】:

在 c++ 中是否有任何函数可以连接一个 int 或我可以编写的一小段代码来做到这一点。到目前为止,我发现的一切似乎都过于复杂。我只是想知道,因为使用字符串你只需将两个字符串相加,所以任何整数等价。

【问题讨论】:

  • 整数的范围是多少?
  • 0 到 9。对于较大的整数有什么不同吗?
  • 不,没有现有的标准函数可以做到这一点,因为这不是人们通常需要做的事情。如果要连接单个数字,则乘以 10,添加一个数字,然后重复(假设您要以 base-10 连接)。
  • 你到底是什么意思?你有“40”和“50”,你想得到“4050”?
  • 哦,好的。我只是觉得很奇怪。谢谢我会尝试所有给定的选项。至少对我来说,似乎所有变量类型都应该构建一个连接运算符/函数,至少我会这样做。只是我的意见。

标签: c++ integer concatenation


【解决方案1】:

我不知道你想达到什么目的

是这样的吗?

#define WEIRDCONCAT(a,b) a##b
int main()
{
cout<<WEIRDCONCAT(1,6);
}

或者可能是这样的:

int no_of_digits(int number){
    int digits = 0; 
    while (number != 0) { number /= 10; digits++; }
    return digits;
}
int concat_ints (int n, ...)
{
  int i;
  int val,result=0;
  va_list vl;
  va_start(vl,n);

  for (i=0;i<n;i++)
  {
    val=va_arg(vl,int);
    result=(result*pow(10,no_of_digits(val)))+val;
  }
  va_end(vl);
 return result;
}

int val=concat_ints (3,  //No of intergers
                     62,712,821); //Example Outputs: 62712821

【讨论】:

    【解决方案2】:

    使用std::to_string

    #include <string>
    std::string s("helloworld:") + std::to_string(3);
    

    输出:helloworld:3

    或者您可以使用 stringstream 来归档您想要的内容

    #include <sstream>
    std::string s("helloworld:");
    
    std::stringstream ss;
    ss << 3;
    s += ss.str();
    

    输出:helloworld:3

    【讨论】:

      【解决方案3】:

      我能想到的最快的方法:

      #include <string>
      
      string constr = to_string(integer1) + to_string(integer2);
      int concatenated = stoi(constr);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2018-10-15
        • 2013-02-26
        • 2011-02-20
        • 1970-01-01
        • 2018-06-22
        相关资源
        最近更新 更多