Reputation: 1395
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
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
Reputation: 49191
Without using strings, you can work backwards. To get the 6,
306 % 10
This will print each digit backwards:
while (num > 0) {
cout << (num % 10) << endl;
num /= 10;
}
Upvotes: 11
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