Bramble
Bramble

Reputation: 1395

int and string parsing

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?

Upvotes: 2

Views: 350

Answers (4)

Learner
Learner

Reputation: 627

Loop string and collect values like

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

Upvotes: 0

pierrotlefou
pierrotlefou

Reputation: 40751

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


  }

Upvotes: 1

Charles Ma
Charles Ma

Reputation: 49191

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

Upvotes: 11

Alexandre Bell
Alexandre Bell

Reputation: 3241

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

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

Upvotes: 2

Related Questions