Int and parsing strings

If I have int say 306. What is the best way to separate the numbers 3 0 6 so that I can use them separately? I was thinking about converting int to string and then parsing it?

int num;    
stringstream new_num;
    new_num << num;

      

I'm not sure how to parse the string. Suggestions?

+2


source to share


4 answers


Without using strings, you can work in the opposite direction. To get 6,

  • It's simple 306 % 10

  • Then divide by 10
  • Go back to 1 to get the next digit.


This will print each digit back:

while (num > 0) {
    cout << (num % 10) << endl;
    num /= 10;
}

      

+11


source


Just move the stream one element at a time and fetch it.



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

      

+2


source


Charles is a very straightforward path. However, it's not hard to convert the number to a string and do some string processing if we don't want to wrestle with the math :)

Here is the procedure we want to do:

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

      

Some language is 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


source


Loop string and collect values ​​like

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

      

0


source







All Articles