Why is the call to c2.view() printing out both the ID and name for the customer ID?
I have stared at this for a while and couldn’t find a cause. I have either missed something really obvious or I don’t understand how cstrings work 🙂
Customer.h
#ifndef CUSTOMER_H
#define CUSTOMER_H
class Customer
{
private:
char accountID[6];
char name[30];
public:
Customer();
Customer(char[], char[]);
void view();
Customer operator=(const Customer&);
};
#endif
Customer.cpp
#include <string>
#include <iostream>
#include "Customer.h"
using namespace std;
Customer::Customer()
{
strcpy(accountID, "");
strcpy(name, "");
}
Customer::Customer(char acc[], char n[])
{
strcpy(accountID, acc);
strcpy(name, n);
}
void Customer::view()
{
cout << "Customer name: " << name << endl;
cout << "Customer ID: " << accountID <<endl;
}
Customer Customer::operator=(const Customer& right)
{
strcpy(accountID, right.accountID);
strcpy(name, right.name);
return* this;
}
Driver.cpp
#include <iostream>
#include "Customer.h"
using namespace std;
int main()
{
char id[] = "123456";
char n[] = "Bob";
Customer c1;
Customer c2(id, n);
c1.view();
c2.view();
system("pause");
return 0;
}
Output:
Customer name:
Customer ID:
Customer name: Bob
Customer ID: 123456Bob
Press any key to continue . . .
You are passing a string with seven characters:
but your array is of size 6. So when you print
accountId, you go beyond the'6'character and print out whatever is next to it, which in this case happens to be the contents ofname.Save yourself a lot of trouble by using
std::stringsinstead of character arrays.