x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 272

# [noob][c++] combining numbers

in python i'd do this

a = "1"
b = "2"

a = a + b = "12"

I need to combine int in c++

a = 12
b = 14

somehow I want to end up with

c = 1214

is there any way to do that?

0
Troudeloup
• 3
• 2
• 2
• +2
8 Solutions

Commented:
Do you want it with strings ? Then :

std::string a = "12";
std::string b = "14";
std::string c = a + b;

or you could do this :

int a = 12;
int b = 14;
int c = (a * 100) + b;
0

Commented:
You can accomplish that this way. I hope, it isn't to complicated.

int a = 12, b = 14;
string stra, strb;
stringstream outa, outb;
outa << a; outb << b;
stra = outa.str();
strb = outb.str();
string strc = stra + strb;

of course you must include string and sstream headers with:

#include <string>
#include <sstream>
0

Commented:
Actually, uusing a stringstream you could just

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

stringstream ss;
int a = 12;
int b = 14;

ss << a << b;

cout << ss.str() << endl;

int c;

ss >> c;

cout << c << endl;
0

Commented:
:-)
0

Author Commented:
is it possible to do it without using strings?

I gave the string example from python just to be an example.
0

Commented:
Did you see my post ?
0

R & D Engineering ManagerCommented:
another way,

int a = 12,b = 14 ;
char c[5];

sprintf(c,"%d%d",a,b);

use strtol() to convert it to long.

Best Regards,
DeepuAbrahamK
0

Commented:
Well, as above:

stringstream ss;
int a = 12;
int b = 14;
int c;

ss << a << b;

ss >> c;
0

Commented:
you can use this function which takes two int arguments and returns another int.

int merge(int a, int b) {
int dec = (int)log10((double)b) + 1;
return a*(int)pow((double)10, dec) + b;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.