일부 문자를 c-string
배열로 복사하는 데 어려움이 있습니다.정확한 문자 수를 복사하는 방법
기본적으로 배열의 크기가 25로 정의되고 사용자가 25자를 입력하면 오버플로이므로 25자를 저장하고 다른 char 배열의 내용을 삭제합니다.
\0
null 종료 문자를 고려해야한다는 것을 알고 있으므로 정확히 25자를 배열에 복사하는 방법이 있습니까?
이 내 헤더 파일 및 코드,
#define FIRSTNAME 25
#define SURNAME 128
#define ADDRESS 128
#define INFORMATION 128
class Customers
{
private:
char firstName[FIRSTNAME];
char surname[SURNAME];
char address[ADDRESS];
char information[INFORMATION];
public:
Customers();
void setFirstName(char *firstName);
void setSurname(char *surname);
void setAddress(char *address);
void setInformation(char *information);
const char* getFirstName() const {return firstName;};
const char* getSurname() const {return surname;};
const char* getAddress() const {return address;};
const char* getInformation() const {return information;};
~Customers();
};
코드입니다 :
이void Customers::setFirstName(char *firstName)
{
strncpy(this->firstName, firstName, FIRSTNAME);
this->firstName[FIRSTNAME - 1] = '\0';
}
void Customers::setSurname(char *surname)
{
strncpy(this->surname, surname, SURNAME);
this->surname[SURNAME - 1] = '\0';
}
void Customers::setAddress(char *address)
{
strncpy(this->address, address, ADDRESS);
this->address[ADDRESS - 1] = '\0';
}
void Customers::setInformation(char *information)
{
strncpy(this->information, information, INFORMATION);
this->information[INFORMATION - 1] = '\0';
}
이 코드는 위의 잘 작동하지만 복사 maximum size - 1
문자 이상. 나는, 모든 문자를 통해 복사하려면 어떻게 ...
void Customers::setFirstName(char *firstName)
{
strcpy(this->firstName, firstName); // IF *firstName is 25 characters, it stores 25 characters and erases what is in the surname variable
}
void Customers::setSurname(char *surname)
{
strcpy(this->surname, surname); // IF *surname is 128 characters, it stores 128 characters and erases what is in the address variable
}
void Customers::setAddress(char *address)
{
strcpy(this->address, address); // IF *address is 128 characters, it stores 128 characters and erases what is in the information variable
}
void Customers::setInformation(char *information)
{
strcpy(this->information, information);
}
을
나는 최대 크기의 문자를 복사하려면 아래에 다음 코드를 시도하지만, 다른 변수에 어떤 삭제합니다 심지어 경우 최대 크기입니까? 예를 들어 성이 실제로 128자인 경우address
변수의 내용을 지우고 싶지 않습니다. 이 문제가 수정 되었습니까?
왜'std :: string' 대신 C-string을 사용하고 있습니까? – Barmar
그래서 C와 C++ 태그를 싫어합니다. – haccks