Hi,

e.g.
int a = 20;
int b = 07;

I want to joint a and b together to get 2007.
Anybody know how to do it?

lots of help,
ken js

This should work:

int a = 20;
int b = 07;

string as = a.ToString();
string bs = b.ToString();

string result = as + bs;
int result_int = Convert.ToInt32(result);

Cheers :)

Here's the simple one

int result = a * 100 + b;

Here's the simple one

int result = a * 100 + b;

And what if he wants to join the following two numbers???
int a = 9999;
int b = 888;

Your solution doesn't work for all numbers :-/

This should work:

int a = 20;
int b = 07;

string as = a.ToString();
string bs = b.ToString();

string result = as + bs;
int result_int = Convert.ToInt32(result);

Cheers :)

And without .net this works.

#include <sstream>

template <class T>
T Join( T a, T b ) {
  std::stringstream ss;
  T result;

  ss<< a << b;
  ss>> result;

  return result;
}

But remember that 07 won't be stringized into "07", it'll be stringized into "7" because the leading zero doesn't mean anything. With either solution the result is 207 instead of 2007.

And your code still isn't valid C++ even with C++/CLI. This works though.

using namespace System;

template <class T>
T Join( T a, T b ) {
  String^ temp = a.ToString() + b.ToString();
  return Convert::ToInt32( temp );
}

here is a safer version which performs sanity checks

#include <sstream>
#include <limits>
#include <cassert>

// returns 0 on overflow
template< typename T > inline T join( T a, T b )
{
  typedef std::numeric_limits<T> limits_type ;
  assert( limits_type::is_specialized && limits_type::is_integer ) ;
  assert( !limits_type::is_signed || ( b>=0 ) ) ;
  std::stringstream stm ;
  stm << a << b ;
  T ab = 0 ;
  stm >> ab ;
  return ab ;
}

You might as well change the name from join to join_unsigned_int while you're at it. ;)

You might as well change the name from join to join_unsigned_int while you're at it. ;)

not really, signed int types are ok if b is not negetive. join( -22, 789 ) gives -22789. however, join( 22, -789 ) would fail an assertion. perhaps, join_integral_types?

signed int types are ok if b is not negetive.

Yeah, join_unsigned_int because signed values abort the program. It doesn't matter if the containing type is signed when you still don't allow signed values. ;)

perhaps, join_integral_types?

Maybe a rule for negative arguments. Like if there's one negative and one positive, the negative is always a and the positive is always b, but if both arguments are negative, the sign is trimmed from b before joining. Or b can't have a sign but the function trims the sign instead of aborting the program. Having a little utility function crash the program because it can't handle '-' isn't cool.

Thanks guys for your help...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.