0

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?

LihO
  • 39,598
  • 10
  • 94
  • 164
brno792
  • 5,979
  • 16
  • 53
  • 70
  • 3
    Lookup sprintf()/snprintf: `snprintf(str, sizeof str, "%d %c", x, c);` – P.P Feb 16 '13 at 23:36
  • Do you just want to print the " " or do you need the string for other purposes? If the former, you should simply use `printf()` to do all the work for you. – Code-Apprentice Feb 16 '13 at 23:39

4 Answers4

3

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

Community
  • 1
  • 1
LihO
  • 39,598
  • 10
  • 94
  • 164
1
char tmp[32]={0x0};
sprintf(tmp, "%d %c", x, c);
printf("%s\n", tmp);

or

printf("%d %c\n", x, c);
jim mcnamara
  • 15,489
  • 2
  • 30
  • 48
1

sprintf() can do what you want:

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

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);
Code-Apprentice
  • 76,639
  • 19
  • 130
  • 241