Search code examples
c++iomanip

How to cut off leading digits? C++


How can I cut off the leading digits of a number in order to only display the last two digits, without using the library. For example:

1923 to 23

2001 to 01

1234 to 34

123 to 23

with only

#include <iomanip>
#include <iostream>

Thanks!


Solution

  • If you're just working with integers I'd suggest just doing mod %100 for simplicity:

    int num =2341;
    
    cout << num%100;
    

    Would display 41.

    And if you need a leading zero just do:

    std::cout << std::setw(2) << std::setfill('0') << num%100 << std::endl;