tags:

views:

196

answers:

4

If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it?

int num;    
stringstream new_num;
    new_num << num;

Im not sure how to do parse the string though. Suggestions?

+2  A: 

Just traverse the stream one element at a time and extract it.

char ch;
while( new_num.get(ch) ) {
    std::cout << ch;
}
Krugar
+9  A: 

Without using strings, you can work backwards. To get the 6,

  1. It's simply 306 % 10
  2. Then divide by 10
  3. Go back to 1 to get the next digit.

This will print each digit backwards:

while (num > 0) {
    cout << (num % 10) << endl;
    num /= 10;
}
Charles Ma
+1  A: 

Charles's way is much straight forward. However, it is not uncommon to convert the number to string and do some string processing if we don't want struggle with the math:)

Here is the procedural we want to do :

306 -> "306" -> ['3' ,'0', '6'] -> [3,0,6]

Some language are very easy to do this (Ruby):

 >> 306.to_s.split("").map {|c| c.to_i}
 => [3,0,6]

Some need more work but still very clear (C++) :

    #include <sstream>
    #include <iostream>
    #include <algorithm>
    #include <vector>

  int to_digital(int c)
  {
   return c - '0';
  }

  void test_string_stream()
  {
     int a = 306;
     stringstream ss;
     ss << a;
     string   s = ss.str();
     vector<int> digitals(s.size());
     transform(s.begin(),s.end(),digitals.begin(),to_digital);


  }
pierr
Note that your `to_digital()` doesn't work for all encodings.
sbi
A: 

Loop string and collect values like int val = new_num[i]-'0'

Learner