Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Building a String for a param? C++

I have a function:
Code:
config.read<int>("input");
How would I do this in C++:
Code:
for (int i = 0; i < 128; i++)

{

 config.read<int>(i + "input");

}

I want to parse the input as 0input, 1input, 2input, etc, through to 127input.

What's the easiest way to do this?
 
something like...

Code:
 char inpt [4];

for (int i = 0; i < 128; i++)

{

 sprintf(inpt,"%d%s",i,"input");

 config.read<int>(inpt);

}

You could also use itoa to convert i to a string, but it's less portable than sprintf
 
Just to clear things up a bit, sprintf is not C++, it's C. If you want to be particular, the C++ way of doing things is to use a stream. Here's a bit on why you should use streams instead of sprintf in C++ http://en.wikipedia.org/wiki/Sprintf#C. ... conversion

The way you would do it is create a string stream, send i to the stream, then send "input" to the stream, and then get your string from there.

would look something like

Code:
 

for(int i = 0; i < 128; ++i){

    std::stringstream mystream;

    mystream << i;

    mystream << "input";

    yourfunction(mystream.str().c_str());

}

 

That might not be exactly right, it's almost 3AM :D You also have to do some includes, I think you need <sstream> and <string>?

My guess would be that sprintf is faster in this case, but it's also not the most "right" way of doing it. In the short term, neither speed nor correctness are likely to affect this program, but it's better to learn the right way because you can optimize later. It's best not to optomize until you know why you are optimizing! :D
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top