What's wrong with my code?!

Hi all - I'm at a loss with this code!

It's supposed to take a string in form of DDMMYYYY then output as DD Month YYYY so if you input 23012010, it would output 23 January 2010.

My problem is it doesnt change the 01 to January..it outputs 2010 instead!

Here is the code in basic (not completed- code is only for 01 at the moment)

Please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string date_change(string);

int main()
{
    string travel_date;
    string travel_day, travel_month, travel_year;
    string better_date;
    string new_month;
    
    cout << "Please enter the date you are travelling (DDMMYYYY): ";
    cin >> travel_date;
    
    travel_day = travel_date.substr(0,2);
    travel_month = travel_date.substr(2,4);
    travel_year = travel_date.substr(4,8);
    new_month = date_change(travel_month);
    
    cout << new_month;
    
    system("pause");
    return 0;
}
    
string date_change(string travel_month){
       if (travel_month == "01"){
          return "January";
          }
}


Time to learn to debug. There's no trick to it. Try running this and seeing if everything is as you expect it to be.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string date_change(string);

int main()
{
    string travel_date;
    string travel_day, travel_month, travel_year;
    string better_date;
    string new_month;
    
    cout << "Please enter the date you are travelling (DDMMYYYY): ";
    cin >> travel_date;
    
    travel_day = travel_date.substr(0,2);
    cout << "travel_day  = " << travel_day << endl;
    travel_month = travel_date.substr(2,4);
      cout << "travel_month  = " << travel_month << endl;
  travel_year = travel_date.substr(4,8);
      cout << "travel_year  = " << travel_year << endl;
  new_month = date_change(travel_month);
    
    cout << new_month;
    
  
    return 0;
}
    
string date_change(string travel_month){
       if (travel_month == "01"){
          return "January";
          }
}


Then, read about the substr method; http://www.cplusplus.com/reference/string/string/substr/

In particular, what that second parameter means.
Last edited on
Moschops you posted that right as I was going to post it -.-
Hi guys,

Thanks for the advice.

I did the above and the problem is that the month has 4 characters.

So if I enter 21012010:

day = 21 (as expected)
month = 0120 (Wrong!)
year = 2010 (as expected)

so is it a substr problem??
There's no problem with substr; the problem is that you're using it wrongly :)

Read the linked page; it explains in detail how to use the substr function.
Topic archived. No new replies allowed.