# Taking a number in the middle of an integer

• 06-28-2012
mgcpovoleri
Taking a number in the middle of an integer
Can anyone help me? I'm trying to do this:

Code:

`cin >> integerNumber`
Let's suppose the user entered '2012'. So, I want to output the third number in this int, in this case, the '1'. How I do that?

Thank you :)
• 06-28-2012
manasij7479
Take the input as a std::string, and print out the third character with the [ ] operator.
• 06-28-2012
mgcpovoleri
Hm... it worked. And if i want to add 1 to this number?
• 06-28-2012
grumpy
Do you know how to add one to a character?
• 06-28-2012
Elysia
Or you can use a little math:
2012 / 10 = 201 (division)
201 % 10 = 1 (modulus)
1 + 1 = 2 (addition)
• 06-28-2012
mgcpovoleri
Quote:

Originally Posted by grumpy
Do you know how to add one to a character?

No .-.
• 06-28-2012
Rodaxoleaux
Quote:

Originally Posted by mgcpovoleri
No .-.

If you take input as as std::string, you're saying you don't know how to APPEND+=! a character to it? Oh sorry, my keyboard went all funky after trying to APPEND an exclamation point.
• 06-28-2012
grumpy
That's not actually what mgcpovoleri asked, Rodaxoleaux. The question was about incrementing a character, not appending a character to a string. Even more elementary than you thought, eh?

Hint to mgcpovoleri: char is an integral type (albeit the character '1' is not numerically equal to 1). How would you add 1 to an integral value?
• 06-28-2012
Rodaxoleaux
Quote:

Originally Posted by grumpy
That's not actually what mgcpovoleri asked, Rodaxoleaux. The question was about incrementing a character, not appending a character to a string. Even more elementary than you thought, eh?

Oh. Oh wow, okay.
• 06-28-2012
mgcpovoleri
Let's ask again: I've a string with value "1", and I've a integer with value '2'. How I add 1 + 2 and get the number 3?
• 06-28-2012
std10093
You could just convert string to int and then add them :)
• 06-28-2012
laserlight
Quote:

Originally Posted by mgcpovoleri
I've a string with value "1", and I've a integer with value '2'. How I add 1 + 2 and get the number 3?

Convert the numeric string to its corresponding integer value then add 2 to that result.
• 06-28-2012
Rodaxoleaux
I never thought I'd view a thread on a computer programming forum where the members would actually have to teach someone how to add 1+1.
• 06-28-2012
iMalc
Quote:

Originally Posted by Rodaxoleaux
I never thought I'd view a thread on a computer programming forum where the members would actually have to teach someone how to add 1+1.

Nah nothing so mundane, it's '1' + 1 in this case.
• 06-29-2012
grumpy
I'll give a hint. Given a character that is a digit ('0', '1', '2', .... '9') subtracting '0' converts to the value (i.e. '1' - '0' = 1, '2' - '0' = 2, etc). The reverse also applies: adding '0' to 1 gives '1'.