Hi!

I have recently started to study C++ and I have already faced many problems. This is something I can't get solved on my own.

1st the program asks the user to type in his/her ID (string). Then it will be splitted in 3 parts: day, month and year. The program is able to set every 3 parts into the correct variables in the correct form but after it starts to write data on the next variable, the previous data vanishes.

For example:
1. The program writes the correct day into the "day" -variable.
2. cout << day; prints the correct day.
3. The program writes the correct month into the "month" -variable.
4. cout << day; prints nothing.

So what have I done wrong?

Here is my code (all this is in the main -function):

string ID;
    cout << "Type in your ID: ";
    cin >> ID;
    
    char day[2];
    char month[2];
    char year[2];
    
    day[0] = ID[0];
    day[1] = ID[1];
    day[2] = '\0';
    
    cout << day << endl;
    
    month[0] = ID[2];
    month[1] = ID[3];
    month[2] = '\0';
    
    year[0] = ID[4];
    year[1] = ID[5];
    year[2] = '\0';
    
    cout << day << "." << month << "." << year << endl;

Thanks!


EDIT: The whole code actually starts to fail after it has written the day -part...

Edited 6 Years Ago by DaHandy: n/a

A simple answer: you put 3 bytes into a 2-byte array.

What actually happens:
The arrays are allocated at the stack, next to each other, in order year/month/day (from lower addresses to higher). month[2] is the same as day[0]. A classic buffer overflow.

Edited 6 Years Ago by nezachem: n/a

This article has been dead for over six months. Start a new discussion instead.