简体   繁体   中英

convert int and char into a string

I have int x and char c . I want to make a new string called str as "xc"; so the int, a space, and the char.

So for example:

x = 5, c = 'k'

//concatenate int and char with a space in between.

so the line printf("%s", str) will print:

5 k

How do I do this in C code?

Use sprintf or snprintf to avoid safety of your code to be built on assumption that your buffer will be always big enough:

char str[100];
sprintf(str, 100, "%d %c", x, c);

But in case the only purpose of str will be to be used it to with printf , then just printf directly:

printf("%d %c", x, c);

...just don't use itoa since "this function is not defined in ANSI-C and is not part of C++"

These questions might help you as well:
How to convert an int to string in C
Converting int to string in c

char tmp[32]={0x0};
sprintf(tmp, "%d %c", x, c);
printf("%s\n", tmp);

or

printf("%d %c\n", x, c);

sprintf()可以做你想做的:

sprintf(str, "%d %c", x, c);

Since you want to print the information out, there is no reason (that I can see) to convert the data into a string first. Just print it out:

printf("%d %c", x, c);

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