PDA

View Full Version : Easy question


nothing
07-15-2003, 09:32 PM
Let's say I have 3 variables:

int x = 1;
int y = 2;
int z = 3;

Now, I want to assign those values to a single variable called foo, so that foo will have the value 123. How do I do that?

DNAunion2000
07-15-2003, 11:58 PM
Originally posted by nothing
Let's say I have 3 variables:

int x = 1;
int y = 2;
int z = 3;

Now, I want to assign those values to a single variable called foo, so that foo will have the value 123. How do I do that?


DNAunion: You could do this:

int foo = (100 * x) + (10 * y) + (1 * z);

(You might want to replace "(1 * z)" with just "z")

nothing
07-19-2003, 01:28 AM
Ok, that way I would get 123 but that's not what I meant. For example; let's consider a program that inputs three numbers and then prints the numbers one next to the other. I would do something like this:

#include <iostream>

using namespace std;

int main()
{
int num1;
int num2;
int num3;

cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

cout << num1 << num2 << num3 << endl;

return 0;
}

Instead of using cout << num1 << num2 << num3 << endl;
I want to assign the values of num1, num2, and num3 to a single variable. How would I do that?

DNAunion2000
07-19-2003, 11:15 AM
nothing: Ok, that way I would get 123 but that's not what I meant. For example; let's consider a program that inputs three numbers and then prints the numbers one next to the other. I would do something like this:


#include <iostream>

using namespace std;

int main()
{
int num1;
int num2;
int num3;

cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

cout << num1 << num2 << num3 << endl;

return 0;
}


Instead of using cout << num1 << num2 << num3 << endl;
I want to assign the values of num1, num2, and num3 to a single variable. How would I do that? [/B]

DNAunion: You can't: not to a fourth integer. Suppose you have a fourth variable named num4 that you try to assign those three values to. Assignments are destructive...they overwrite what currently exists in that memory location with the new value.

So we start with num1 = 1, num2 = 2, num3 = 3, and num4 is blank.

num4 = num1;

Works fine.

num4 = num2;

Now you've overwritten num4's previous value. That is, num4 no longer contains anything related to num1.

num4 = num3;

Now you've overwritten num4's previous value, which was num2's value: so you've lost both num1 and num2.

******************************

If I am following you, you need to either:

1) Do as I suggested originally. Assuming 1-digit integers are used, mutliply each variable by its place value and store the result to the fourth variable.

num4 = (100 * num1) + (10 * num2) + (1 * num3);

But this works only if the user enters 1-digit values each time (which is what your example used)


2) Switch variable types: create a string variable to hold the three variables' string representations, tacked together back to back.