Functions with variable number of arguments

I've been assigned 4 problems for my C++ class, and this is one of those problems. I'm not really sure where to start. Help would be appreciated, thank you in advance.


Write a function write with variable number of arguments that takes a string first argument followed by any number of arguments of type double and prints on the screen a string formatted by the rules described below. The first argument may contain formats in curly braces of the form {index[:specifier]}, where the square brackets show optional parts (this is :specifier may be missing), and index is the sequence number of an argument of type double (starting from sequence number 0).

Rules for formatting: In the printed string the curly brackets and their content will be replaced by the argument with the given index, formatted according to the given format specifier. If the format specifier is missing, the argument will be printed with its default format. For example:

write("The number {0} is greater than {1}.", 5, -3);
will print
The number 5 is greater than -3.

write("There are no format specifiers here.");
will print
There are no format specifiers here.

The format specifiers and their meanings are listed in the following table

Specifier  Meaning	Format 	Output for 1.62    Output for 2.0
none	 default	 {0}	1.62    	   2
c	currency	{0:c}	$1.62	           $2.00
e	scientific	{0:e}	1.620000e+000	   2.000000e+000
f	fixed point	{0:f}	1.620000	   2.000000
i	round to int	{0:i}	2	           2


Limitations: You may limit the maximum number of arguments your function can process to a certain value, for example 10.

Suggested extensions:
• add an optional alignment specification in the format , e.g., make the format of the form {index[,alignment][:specifier]}, where alignment is an integer specifying the width of the field in which the corresponding argument will be printed. If alignment is positive, align to the right, if it is negative, align to the left.
• Accept an optional integer after the specifier letter, specifying the required precision in the output. For example, {0:f2} will print the number 1.6234 as 1.62, but {0:f5} will print it as 1.62340.
Last edited on
However, you should be able to work your way through it. Start with the examples found here
http://www.cplusplus.com/reference/cstdarg/

You don't have to worry about what type of value to retrieve -- your homework says they are all to be type double, so you should always
obtain them with:

double x = va_arg( arg_list, double );

Once you have that value, you can use all the standard C++ stream formatting stuff to print it.

For example, to round to int, just do it the normal way:

cout << (int)x;

Have fun.
Topic archived. No new replies allowed.