Need some help with C++, Please!

Started by
5 comments, last by Peddler 24 years, 3 months ago
Hi, I have been trying to figure out how to tackle this issue for awhile and it is driving me insane. I have an integer which holds my games score, it is 6 digits long. I want to be able to read the first digit and copy it into a new integer, the second digit into a new, third, etc.. Does anyone have any tips that could help me out? Thanks a lot, Tim Yarosh
Advertisement
Well, the easiest way I could think of is convert the sucker to a string, and then pull each character one at a time into a seperate integer.
Potsticker''s right:

int score = 123456;
int digits[6];
char buf[8]; sprintf(buf, "%06d", score);
for (int q=0; q < 6; q++) {
digits[q] = buf[q] - 48; // ASCII ''0''
}

That code''ll take the variable score and put its digits in the digits array. The %06d tells sprintf to pad the string with zeros so that it''s always 6 chars long, so if you score is 123, it prints 000123. 48 is the ASCII code for zero.

Hope it helps...



Mason McCuskey
Spin Studios - home of Quaternion, 2000 GDC Indie Games Fest Finalist!
www.spin-studios.com
Founder, Cuttlefish Industries
The Cuttlefish Engine lets anyone develop great games for iPad, iPhone, Android, WP7, the web, and more!
Or, you could do it the mathematical way:

int score = 654321;
int digits[6];

int tempScore = score;
for (int i=0; i<6; i++)
{
digits = tempScore % 10; // == digit in 1's place<br> tempScore /= 10; // /= 10 means move everything down one place<br>}<br><br>Edited by - Stoffel on 1/13/00 2:24:16 PM
mason, I''m surprised you didn''t mention the strstream method!

strstream str;

str.width(6);
str.fill(''0'');
str << score;

for (i = 0; i < 6; i++) {
char a;
a << str;
digits = a - ''0'';
}
Another way would be to print the number to the screen and get the displayed picture into a buffer and run an OCR algorithm (OCR - optical character recognization) to identify the characters from the picture.

by the way - just kiddin... dont even try this way!
Hey, old habits die hard. At my core I''m still an old-fashioned C programmer.

I catch all sorts of flak for using open()/close() instead of iostreams, too.

You always trust what you learn first. I''m just glad I learned C before I learned Pascal.



Mason McCuskey
Spin Studios - home of Quaternion, 2000 GDC Indie Games Fest Finalist!
www.spin-studios.com
Founder, Cuttlefish Industries
The Cuttlefish Engine lets anyone develop great games for iPad, iPhone, Android, WP7, the web, and more!

This topic is closed to new replies.

Advertisement