Skip to main content
gamedev.net
🔒 Locked

[C++] Beginner problem

Started by PureSnowX 3 replies 1.1k views
Original Post
PureSnowX
PureSnowX
Well I didn't know how to describe the problem in the topic title so here we go!

The program takes number for input ( lets say "123" ), I'll need to program to add that number together into a new number like: 1+2+3 = 6.
I thought the easiest way to do this was to convert the INT into a string then use substring and then convert them back into int's and add them together.

But I'm sure there is an easier way to do this so please tell me



BTW. I don't know if this is the right section but the "Beginner" section is for game-programming as i understand it
MilchoPenchev
MilchoPenchev
Easier way to do that would be to use the integer remainder and divide operators. ( the % and / )

If you've got an arbitrary (non-negative) integer input you can add the digits together like this:



int input, sum = 0;

// get input from user here

while (input != 0)

{

sum += input % 10;

input = input / 10;

}

rip-off
rip-off
Another option is to neither read the input as a string or a number. Instead, read it character by character, and sum these directly.

Note that a program that uses your substring() method, or reads character by character, could handle 477,218,588 digits*. Reading the value directly into an integer like Milcho shows would only handle 10 digits*.

* [size="1"]Assuming you are using a 32 bit unsigned integers
PureSnowX
PureSnowX
How do you read the input digit by digit ?


EDIT:
Something like:

[font=verdana, geneva, lucida,]char number[MAX_DIGITS];
cin >> number;[/font]


?
rip-off
rip-off
That code will read a string into a fixed size buffer - almost certainly causing buffer overflow errors for the number of digits I was talking about, unless you were very generous with MAX_DIGITS.

I meant using a single character at a time:

#include <iostream>
#include <cctype>

int main()
{
char c;
while(std::cin >> c)
{
if(std::isdigit(c))
{
std::cout << "Got a digit: " << c << '\n';
}
else
{
std::cout << "Not a digit: " << c << '\n';
}
}
}

Converting a character to a number can be done in many ways. A simple one* is to subtract the character value '0' from the integer representation of the character. E.g.

int n = c - '0';

Remember that the textual character 0 is actually represented by a different number than the bit pattern 0*. In ASCII and 8 bit Unicode, this happens to be the bit pattern for 48.

Notice:

  • '0' - '0' = 0
  • '1' - '0' = 1
  • ...
  • '9' - '0' = 9


    * [size="1"]I'm ignoring text encoding here, to simplify. I'm also assuming character encodings for numbers begin with 0 and are contiguous.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.