Date Help

Does someone have a quick code for converting strings to Dates in C++.

Example: What is the date:
User response: 12/05/14

Can someone tell me a way I can code this to recognize it as a date, and make it so that the date is sortable? Not referring to the system date, but a user input date.

Any help will be appreciated.

Are you trying to convert the input string to an actual date structure or...?

If you just need to take a date in string format and split it into ints, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int month,
    day,
    year;

string input;
stringstream ss;

cout << "What is the date: ";

cin >> input;

for(int i = 0; i < input.length(); ++i)
     input[i] = input[i] == '/' ? ' ' : input[i];

ss << input;

ss >> month >> day >> year;


You'll just need stringstream:
#include <sstream>
Last edited on
Yes, I am trying to take the inputted string value, and make it into intergers. Please explain the
1
2
for(int i = 0; i < input.length(); ++i)
     input[i] = input[i] == '/' ? ' ' : input[i];


Trying to understand what is going on here. It looks simple enough that it may work for me.
This part goes through every character in the input string and replaces slashes with spaces.

I just used an inline IF statement; it's the same as:
1
2
3
4
5
for(int i = 0; i < input.length(); ++i)
{
     if(input[i] == '/')
          input[i] = ' ';
}
Gotcha!!

Thanks, will try this out!!
Topic archived. No new replies allowed.