C ++结合了3个整数

时间:2014-06-19 19:57:44

标签: c++ arrays join integer concatenation

我需要从某个区域加入3个整数 如参见

int sens1[]= {11,22,13,66,2};

int x= ?? // and here i need to join sens1[0], sens1[1] and sens1[2] 
          // so the X to be=112213 not like char, like integer value

3 个答案:

答案 0 :(得分:6)

我认为您可以使用stringstream来实现此目的:

int result;
stringstream ss;
ss << sense1[0] << sense1[1] << sense1[2]; //assumes sense1[0,1,2] are all integers
ss >> result; //might need to be careful of integer overflow if it is too long

基本上将它们连接成一个字符串并将其读回一个整数。

答案 1 :(得分:0)

您可以使用sprintf()和atol():

char str[255];
long result;
sprintf(str, "%i%i%i", sense1[1], sense1[2], sense1[3]);
result=atol(str);

答案 2 :(得分:0)

std::string s = "";
for(int i=0; i<3; ++i)
    s += std::to_string(sens1[i]);
int n = strtol (s.c_str(), NULL, 10);