brno792
brno792

Reputation: 6799

convert int and char into a string

I have int x and char c. I want to make a new string called str as "x c"; 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?

Upvotes: 0

Views: 240

Answers (4)

LihO
LihO

Reputation: 42093

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

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83537

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);

Upvotes: 1

sprintf() can do what you want:

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

Upvotes: 1

jim mcnamara
jim mcnamara

Reputation: 16389

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

or

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

Upvotes: 1

Related Questions