-4

I am new to working with arrays in C and I am trying to store a string like so:

//x, y, p are floats
("X: %f\nY: %f\nP: %f", x, y, p)

into an array.

I do not know how to read in the values x, y, p so that the array stores it as a single string.

Is it possible? If not, how should I do this?

UPDATE

So apparently people don't understand what I mean.

The above is not my specific code, it is the string I wish to store; an example.

printf("X: %f\nY: %f\nP: %f", x, y, p); 

is equal to when printed in the command:

X: 10.000000
Y: 12.000000
P: 32.000000

This is how I wish to store it in an array, instead, it is recognising it as 4 arguments, instead of 1.

  1. the string = "X: %f\nY: %f\nP: %f"
  2. x
  3. y
  4. p

How can I make it recognise it as one argument?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
App Dev Guy
  • 5,396
  • 4
  • 31
  • 54

1 Answers1

1

You can use sprintf or snprintf. Here array is your C-string array (char *array[n]):

array[x] = malloc(64);
snprintf(array, 64, "X: %f\nY: %f\nP: %f", x, y, p);

snprintf is safer because you can set the maximum number of characters it should write.

I picked the magic number 64 here, but you should make sure to allocate enough memory to store the result string with the converted floats.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • That is perfect. Thank you a million my friend. I am glad you understood what I was meaning, I copped a lot of hate on this question. – App Dev Guy Aug 10 '15 at 15:02