質問

I am doing the following assignment in C++. I have an array of chars

char myyear[4] = { dob[0], dob[1], dob[2], dob[3] };
char mymonth[2] = {dob[4], dob[5]};
char mydate[2] = { dob[6], dob[7] };

and I wrote:

cout<<myyear<<"-"<<mymonth<<"-"<<mydate<<"-"<<endl;

and I got the output

1981╕■#-051981╕■#-02051981╕■#

and not

1981-05-02

which is what dob contains.

Any help.

役に立ちましたか?

解決

You need to include null terminators at the end of each of your character arrays.

For example,

char myyear[5] = { dob[0], dob[1], dob[2], dob[3], 0 };

cout (along with many other string-type functions in C and C++) requires a string to be modelled as a sequence of characters terminated by a 0.

What you are doing at the moment is, technically, undefined behaviour: the fact that you are getting any output at all is to be considered entierly coincidental.

By the way, why are you modelling the numeric values like this? std::cout also works for integer types: e.g. int myyear = 1981; cout << myyear; is perfectly valid.

他のヒント

Probably you need a \0 (null termination) at the end.

char myyear[5] = { dob[0], dob[1], dob[2], dob[3], '\0' };
char mymonth[3] = {dob[4], dob[5], '\0'};
char mydate[3] = { dob[6], dob[7], '\0'};

You need to null terminate each of the arrays. See character sequences

const char NULL_TERMINATOR = '\0';
char myyear[5] = { dob[0], dob[1], dob[2], dob[3], NULL_TERMINATOR };
char mymonth[3] = {dob[4], dob[5], NULL_TERMINATOR };
char mydate[3] = { dob[6], dob[7], NULL_TERMINATOR };
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top