我有问题将 3 个变量合并为一个变量:
例子 :
int var1,var2,var3;
int result;
var1 = 1;
var2 = 2;
var3 = 3;
result = ........??;
printf("Result %d",result);
output :
123
我怎样才能做到这一点?
result = var1 * 100 + var2 *10 + var3;
printf("结果 %d%d%d",var1, var2, var3);
是的,C++11 可变参数模板很棒!这是一个N
可无限扩展的版本,假设sum(args) < INT_MAX
template<int max, int ...arguments>
int merge_integers()
{
int args[] = { arguments... };
int size = sizeof(args) / sizeof(int);
int mul = 1;
int result = 0;
for (int i = size; i--; )
{
result += args[i] * mul;
mul *= max;
}
return result;
}
示例用法:
printf("%d\n", merge_integers<10, 5, 4, 3, 2, 1>());
printf("%x\n", merge_integers<16, 0xA, 0xB, 0x1, 0x3, 0x5>());
printf("%o\n", merge_integers<8, 1, 2, 3, 4, 7>());
输出:
54321 ab135 12347
应该是:
char str[100];
sprintf(str, "%d%d%d", var1, var2, var3);
sscanf(str, "%d", &result); // or atoi
如果您不知道变量有多少位数,则必须通过 stringstream:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 10;
int b = 12;
int c = 2;
stringstream ss;
ss << a << b << c;
int merge;
ss >> merge;
cout << merge << endl;
return 0;
}
ideone上的工作示例。
你真的需要 int 变量吗?字符串是否满足您的要求?
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int
main()
{
int var1 = 1;
int var2 = 2;
int var3 = 3;
ostringstream oss;
string result;
oss<<var1<<var2<<var3;
result = oss.str();
cout<<result<<endl;
return 0;
}