Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int and string parsing

Tags:

c++

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?

like image 512
Bramble Avatar asked Jul 10 '26 12:07

Bramble


2 Answers

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;
}
like image 182
Charles Ma Avatar answered Jul 12 '26 02:07

Charles Ma


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

char ch;
while( new_num.get(ch) ) {
    std::cout << ch;
}
like image 23
Alexandre Bell Avatar answered Jul 12 '26 01:07

Alexandre Bell