Improve company productivity with a Business Account.Sign Up

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

[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
Asked:
Troudeloup
  • 3
  • 2
  • 2
  • +2
8 Solutions
 
Infinity08Commented:
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
 
UrosVidojevicCommented:
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
 
jkrCommented:
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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
UrosVidojevicCommented:
:-)
0
 
TroudeloupAuthor Commented:
is it possible to do it without using strings?

I gave the string example from python just to be an example.
0
 
Infinity08Commented:
Did you see my post ?
0
 
Deepu AbrahamR & 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
 
jkrCommented:
Well, as above:

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

ss << a << b;

ss >> c;
0
 
UrosVidojevicCommented:
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.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 3
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now