Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have printf() properly print out an array (of floats, say)?

Tags:

I believe I have carefully read the entire printf() documentation but could not find any way to have it print out, say, the elements of a 10-element array of float(s).

E.g., if I have

float[] foo = {1., 2., 3., ..., 10.}; 

Then I'd like to have a single statement such as

printf("what_do_I_put_here\n", foo); 

Which would print out something along the lines of:

1. 2. 3. .... 10. 

Is there a way to do that in vanilla C?

like image 654
lindelof Avatar asked Dec 09 '11 08:12

lindelof


People also ask

Can you make a float array in C?

You can't create an array with no static size. You can create an array like this on the stack, which is mostly when you have smaller arrays: float myarray[12]; it is created in the scope and destroyed when that scope is left.

Can you print an array in C++?

We can use Ostream iterators to write to an output stream. The idea is to use an output iterator std::ostream_iterator to print array contents to std::cout with the help of std::copy , which takes input iterator to the starting and ending positions of the array and the output iterator.

What does %% do in printf?

It is an escape sequence. As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.


2 Answers

you need to iterate through the array's elements

float foo[] = {1, 2, 3, 10}; int i; for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {     printf("%lf\n",foo[i]); } 

or create a function that returns stacked sn printf and then prints it with

printf("%s\n",function_that_makes_pretty_output(foo)) 
like image 124
jackdoe Avatar answered Sep 22 '22 14:09

jackdoe


You have to loop through the array and printf() each element:

for(int i=0;i<10;++i) {   printf("%.2f ", foo[i]); }  printf("\n"); 
like image 32
ckruse Avatar answered Sep 23 '22 14:09

ckruse