简体   繁体   中英

C: how to concatenate a number between two c-style null-terminated character arrays using strncat?

I have the following code and am trying to get a C-style null-terminated string after concatenating two C-Style strings and an integer in the middle.

const int NUMBER_APPLES = 6;

char Parameter_Complete[504] = "You have ";
char Parameter_End[8] = " apples";

char number[2];
number[0] = (char)NUMBER_APPLES;
number[1] = '\0'

strncat(Parameter_Complete, number, sizeof(Parameter_Complete));
strncat(Parameter_Complete, Parameter_End, sizeof(Parameter_Complete));

When I printf "Parameter_Complete", it says:

"You have < UNREADABLE CHARACTER > apples"

... instead of "You have 5 apples".

Can someone give me a hint on what might be wrong?

When you cast an integer into a char in C, it keeps its value, but is now used as an ASCII character. This means that (char)6 would be equal to '\\x06', which is not what you want.

What you do want is snprintf . This allows you to fill in a format string and put its output into another string.

... same code ...
char output[1000];
snprintf(output, 1000, "%s%d%s", Parameter_Complete, number, Parameter_End);

Or, if your two string variables are always going to be constant, you could just do:

const int number = 6;
char output[1000];
snprintf(output, 1000, "You have %d apples.", number);

maybe use sprintf or snprintf instead?

char number[32];
sprintf(number, "%d", NUMBER_APPLES)

number[0] = (char)NUMBER_APPLES; is just 6 so it would replaced by ascii character equivalent to 6 which is non printable i think you should replace it by this number[0] = '0' +(char)NUMBER_APPLES the ascii character equivalent is '6'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM