Jump to content
  • Advertisement
Sign in to follow this  
sixteen

combining string & ints to = variable

This topic is 4352 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This oututs: dude0 dude1 However, I want it to output: file0.g file1.g So basically, instead of "dude" + myStream.str() coming out to be strings, I want it to recognize them as the variables dude0 and dude1 so they cout the values, which are of course file0.g and file1.g
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string dude0 = "file0.g";
string dude1 = "file1.g";

main()
{
	for(int i=0;i<2;i++)
	{
		ostringstream myStream;
		myStream << i << flush;
		cout << "dude" + myStream.str() << endl;
	}
	cout << endl;
	system("PAUSE");
	return 0;
}


Share this post


Link to post
Share on other sites
Advertisement
Nice simple answer for you - you can't in C++.

Once your code is compiled, the variable names are GONE and do not exist in your executable. I guess you are coming from a background like javascript, or possibly the Flash background the guy here the other day asking the same question had.

You would need to do this instead for a properly compiled language:


string dude[2];

void init()
{
dude[0]="file0.g";
dude[1]="file1.g";

// or

for(int i=0;i<2;++i)
{
ostringstream myStream;
myStream << "file" << i << ".g" << flush;
dude=myStream.str();
}
}

int main(int,const char **av)
{
init();
for(int i=0;i<2;++i) cout << dude << endl;
}






Sorry. HTH

Share this post


Link to post
Share on other sites
If I understand you correctly, what you are trying to do is not really possible. Why don't you just store them in arrays?

#include <iostream>
#include <string>

using namespace std;

int main( )
{
string dude[2];
dude[0] = "file0.g";
dude[1] = "file1.g";

for(int i=0;i<2;i++)
{
cout << dude << endl;
}
cout << endl;

return 0;
}



What you are attempting falls under the category of generating code on the fly using strings. If you really have to do this, consider using a scrpting language like Lua.

Share this post


Link to post
Share on other sites
I don't think this can be done in C++. There is no way you can enumerate variables as it is possible in Java/C#.
But why don't you use array?

#include <string>
#include <iostream>

using namespace std;

const string dudes[] = {"file0.g", "file1.g"};

int main(int argc, char **argv)
{
for (int i = 0; i < 2; ++i)
{
cout << dudes << endl;
}

cout << endl;

return 0;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!