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?

3
  • 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... Commented Sep 11, 2009 at 4:07
  • Prince Charles would write "indices". Commented Sep 11, 2009 at 6:33
  • Seems an exact duplicate for me: stackoverflow.com/questions/1397737/… Commented Sep 11, 2009 at 6:39

4 Answers 4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

char ch;
while( new_num.get(ch) ) {
    std::cout << ch;
}

Comments

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


  }

1 Comment

Note that your to_digital() doesn't work for all encodings.
0

Loop string and collect values like

int val = new_num[i]-'0';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.