-5

I would like to concatenate x number of variables into 1 int.

for example:

int i = 6;
int a = 5;
int b = 1;
int x = 9;
int z = 4;

int num = i && a && b && x && z;

cout << num;

I want num to display this number: 65194

4

4 回答 4

6

For numbers you can use basic arithmetics:

int num = ((((i * 10) + a) * 10 + b) * 10 + x) * 10 + z;
于 2013-10-26T15:36:58.013 回答
5

Just use a std::vector

Then use std::vector::push_back to insert the elements into it.

std::vector<int> my_vector;
my_vector.push_back(6);
my_vector.push_back(5); // push the rest of the numbers

To display the contents:

for(auto& i: my_vector)
    std::cout << i;
于 2013-10-26T15:32:04.710 回答
1

First of all, declare a string and then convert the numbers to string using one of the methods below. This is just one method, there are other methods to do this also.

  1. Check out itoa function.
  2. Another way is:

    int a = 10;

    char *intStr = itoa(a);

    string str = string(intStr);

  3. Yet another way:

    int a = 10;

    stringstream ss;

    ss << a;

    string str = ss.str();

  4. Other than that, C++11 has two new functions:

于 2013-10-26T16:46:06.927 回答
-1

The && operator is logical and operator.

In it's simplest form, it works like:

(condition 1) && (condition 2)

(It's precedence is from left to right.)

If condition 1 is true ( the condition will return 1) it will advance to the right and evaluate the second condition. If it finds the second condition to be also be true, the result will be:

1 && 1 which will eventually be 1 as TRUE AND TRUE = TRUE

now coming onto your query:

int i = 6; int a = 5; int b = 1; int x = 9; int z = 4;

int num = i && a && b && x && z;

cout << num;

Unless there is a zero in here, the output will always be 1, as the && operator is treating the values of the variables like the results of a condition check (a positive integer for true and 0 for false). So num will always be 1 unless one of the variables is 0.

So, now that you understand && operator does not works like you expected, you should have understood it isn't feasible.

于 2013-10-27T12:25:08.217 回答