0

Currently working on a Lottery project for my CompSci class.

I've got 40 lottery ball images (1.BMP to 40.BMP) and I want to use a for loop to display each ball.

I can display them just fine if I call displayBMP all 40 times, but there has to be a prettier way of doing this.

string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    char alphanum = i;
    //char* name = combine alphanum and type
    displayBMP(name, randomX(), randomY());
}

Edit

Trying to put this junk in .cpp file for my header.

#include "Lottery.h"
void Lottery::initDisplay()
{

    //Draw Some Lines

    //Display Lottery balls 1-40

}

Any thoughts?

cerealspiller
  • 1,401
  • 3
  • 14
  • 23

2 Answers2

0

I think you want:

1.BMP
2.BMP
3.BMP
4.BMP

etc..

The code for that would be:

Non-C++11:

#include <sstream>

template <typename T>
std::string ToString(T Number)
{
    std::stringstream ss;
    ss << Number;
    return ss.str();
}

std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    displayBMP(ToString(i) + type, randomX(), randomY());
}

Using C++11:

std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    displayBMP(std::to_string(i) + type, randomX(), randomY());
}
Brandon
  • 22,723
  • 11
  • 93
  • 186
  • The first 2 options look good but I'm getting the following error ['displayBMP' : cannot convert parameter 1 from 'std::string' to 'char *'] – cerealspiller Oct 27 '13 at 05:44
  • To convert a `name` to a `const char*`, you need to do `.c_str()`. I don't know the definition of your displayBMP function.. If displayBMP does NOT need to modify the name parameter, then it is safe to do: `displayBMP(const_cast(name.c_str()), .....);` – Brandon Oct 27 '13 at 05:46
  • Just saw your edit. The Non-C++11 options looks like it will work, just need to implement that into my .h file... some how... Yeah. not sure where to place the template :( – cerealspiller Oct 27 '13 at 05:50
  • I'm failing at trying to work your code. It all looks solid but I'm just doing it wrong. I'll edit my question... – cerealspiller Oct 27 '13 at 05:58
0

You can use function c_str() in string class to return const char*

So if the first type of displayBMP is const char*

e.g.

std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    char alphanum = i;

    std::string name = "" + alphanum + type;
    displayBMP(name.c_str(), randomX(), randomY());
}

However, the type is char*

e.g.

std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
  char alphanum = i;

  std::string name = "" + alphanum + type;
  displayBMP(&name[0], randomX(), randomY());
}

Here, I suggest that convert the name's type to string that will be more convenient, and if you don't want to change the name in the displayBMP, the first example will be more intuition

RyanLiu
  • 1,557
  • 2
  • 18
  • 27