views:

113

answers:

2

How can I cut off the leading digits of a number in order to only display the last two digits, without using the library. For example:

1923 to 23

2001 to 01

1234 to 34

123 to 23

with only

#include <iomanip>
#include <iostream>

Thanks!

+6  A: 

If your numbers are in int form (rather than string form), you should think about using the modulo operator.

If the numbers are in char[] form, there is an easy solution that involves indexing into the string, like:

char *myString = "ABCDE";
int lengthOfMyString = 5;
cout << myString[lengthOfMyString - 3]
     << myString[lengthOfMyString - 5]
     << myString[lengthOfMyString - 4];
//outputs the word CAB
Jon Rodriguez
Wow thanks, that was extremely simple. I was definitely over thinking that one.
dubyaa
Great, I'm glad I could help. It would be wonderful if you could please click the check mark in order to officially accept my answer.
Jon Rodriguez
To display only the last two characters (as asked), it's `cout << ` For both, you should know or check that the string has at least 2 characters first.
Tony
+5  A: 

If you're just working with integers I'd suggest just doing mod %100 for simplicity:

int num =2341;

cout << num%100;

Would display 41.

And if you need a leading zero just do:

std::cout << std::setw(2) << std::setfill('0') << num%100 << std::endl;
Jacob Schlather
That's what I thought when I read the question. Cool.
slashmais
This is much simpler, you got my vote (since his question implies he isn't working with strings, no #include <string>)
Marlon
You need to set the ostream width and fill character, else this code does not emit the leading zeros. `std::cout << std::setw(2) << std::setfill('0') << 3 << '\n';`
Rudi
Thanks Rudi, I thought about that when I was first answering the question, but it slipped my mind to actually put it in - included.
Jacob Schlather