Indexing an Integer Variable

Jul 14, 2012 at 6:06am
Whats the best way to go about indexing a number? For example, if i wanted to check to see if an integer had certain characters in it how would I do that?

Thanks,
Nick
Jul 14, 2012 at 6:15am
C++ way seems to be stick into a stringstream, then convert that to a string. From there, you can index all day. This is probably the simpler way. The C way, woul be to create a char array, and do some modulus math and stick each integer into the array.
Jul 14, 2012 at 6:32am
Why use strings or characters? Isn't an int array easier?
Jul 14, 2012 at 6:34am
How are you going to separate each digit, though? Can't just take an int and throw it at an int array and have each digit in it's own index :)
Jul 14, 2012 at 6:42am
I think OP is confused. An integer is an atomic entity. It's not built out of smaller parts that you can disassemble. The number 24 is the number 24, not the numbers 2 and 4 put a specific order.
Jul 14, 2012 at 6:42am
Reference my Palindrome function:
1
2
3
4
5
6
7
8
9
10
11
12
bool IsPalindrome(int number) {
   std::vector<int> myPalindrome;
   // Specifically here
   while(number) {
      myPalindrome.push_back(number % 10);
      number /= 10;
   }
   for(unsigned int i = 0; i < myPalindrome.size() / 2; i ++)
      if(myPalindrome[i] != myPalindrome[myPalindrome.size() - i - 1])
         return false;
   return true;
}


Simple modulus and division my dear friend. And if the order of numbers matter, just reverse the array/vector to get them lined up correctly.
Topic archived. No new replies allowed.