Abinash Nanda
Abinash Nanda

Reputation: 57

Extra Characters getting added in C++ for char array data type

I have the following code, where the booking_id is calculated using a function.

void calculateBookingID(char* id);
class BookFlight
{
public:
    char booking_id[5];
    void addBooking()
    {
        string dummy;
        calculateBookingID(booking_id);
        cout << "Enter Airline ID : ";
        cin.getline(airline_id,3);             

    }
    void displayBooking()
    {       
            cout << booking_id <<'\t'<<airline_id<<endl;       
    }

private:
    char airline_id[3];

} b1,b2;

string getNextBookingID(string ID);

int main()
{
    b1.addBooking();
    b1.displayBooking();
    return 0; 
}

void calculateBookingID(char* id)
{  
        strcpy(id,"B1001");
}


For some reason in the booking_id the airline_id is also getting added. In the debugger the values look fine, but while displaying it adds 2 extra characters.

Example output:

B1001CD CD

Here the booking_id is B1001CD, where as it should be B1001

I am unable to figure out what is wrong. Can someonce please advise what have I done wrong? Regards, Abinash

Upvotes: 1

Views: 692

Answers (2)

Sisir
Sisir

Reputation: 5388

As you have figured it out changing the booking_id to char booking_id[6] will fix your current problem. However consider the following points for improvement in your code:

  1. Make the fields booking_id and airline_id reasonably big enough like 100 chars to accommodate error handling. It will be much better if you can make them dynamic as well.
  2. Make booking_id private
  3. Make calculateBookingID() a private class method. Try avoiding free functions while coding in C++
  4. Use strcpy_s instead of strcpy as the later is depricated.
  5. Avoid global scope objects, instead create b1 and b2 inside main() where you need them.

Upvotes: 1

Abinash Nanda
Abinash Nanda

Reputation: 57

Got it, booking_id needs to be of 6 characters to accomodate the null.

Thanks, Abinash

Upvotes: 0

Related Questions