Jump to content

C++ Substring for Integers or setting max width for Integers?

Go to solution Solved by Ciccioo,

if you want to extract the last two digits of a number, you can just work on the integer using modulo

2014 % 100 = 14

 

this way the user can enter the year in whatever format, because

2014 % 100 = 14

14 % 100 = 14

Hi , I'm currently working on a project for my c++ course in which a user enters 3 different numbers for a date. The program then will ask them which of the following formats would they like their output. 

1. 10/7/14

2. October 7, 2014

3. 7-Oct-2014

 

I can handle everything but the first option. If the user entered 2014 for his/her year, how would i make sure the program only displays 14 instead of 2014?

Link to post
Share on other sites

You grab the whole line, and separate each into 3 strings through substringing such that

string day = "10", month = "7" and year = "2014"

for year, simply check for size of the string.

if(year.size() == 4)

   substring one more time to extract the last 2 digits

you can then use stringstream or stoi to convert and check day/month

month first depending on year(if leap feb has 29) then day depending on month

Link to post
Share on other sites

if you want to extract the last two digits of a number, you can just work on the integer using modulo

2014 % 100 = 14

 

this way the user can enter the year in whatever format, because

2014 % 100 = 14

14 % 100 = 14

Link to post
Share on other sites

if you want to extract the last two digits of a number, you can just work on the integer using modulo

2014 % 100 = 14

 

this way the user can enter the year in whatever format, because

2014 % 100 = 14

14 % 100 = 14

Thank you SO MUCH. I completely forgot about that operator, and thanks for the simple solution. Much appreciated.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×