2

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?

Bramble
  • 1,395
  • 13
  • 39
  • 55
  • If you use stringstream for conversion, then "parsing" the string is just a matter of accessing it through indexes. For example, if your string is toto. toto[0] will be 3, toto[1] 0... – anno Sep 11 '09 at 04:07
  • Prince Charles would write "indices". – Kirill V. Lyadvinsky Sep 11 '09 at 06:33
  • Seems an exact duplicate for me: http://stackoverflow.com/questions/1397737/how-to-get-the-digits-of-a-number-without-converting-it-to-a-string-char-array/ – SadSido Sep 11 '09 at 06:39

4 Answers4

11

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;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Charles Ma
  • 47,141
  • 22
  • 87
  • 101
2

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

char ch;
while( new_num.get(ch) ) {
    std::cout << ch;
}
Alexandre Bell
  • 3,141
  • 3
  • 30
  • 43
1

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);


  }
pierrotlefou
  • 39,805
  • 37
  • 135
  • 175
0

Loop string and collect values like

int val = new_num[i]-'0';
thkala
  • 84,049
  • 23
  • 157
  • 201
Learner
  • 597
  • 1
  • 5
  • 17