473,785 Members | 2,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to write such a function?

How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?

Thanks for for your help!
Jul 22 '05 #1
6 1575
tings wrote:
How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?

Thanks for for your help!

See, for example:

http://www.gnu.org/software/libc/man...adic%20Example

Of course, you *could* have searched the web for `variadic function
C++'...but I'll give you this one as a freebie. ;-)

[Of course, since this is news:comp.lang. c++, the include you should use
is <cstdarg> as opposed to <stdarg.h>.]

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/20)
http://www.cafepress.com/goldsays
Jul 22 '05 #2
On Sun, 09 Jan 2005 19:15:07 GMT in comp.lang.c++, "tings"
<ti******@hotma il.com> wrote,
How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?


/* VA_EXAMP.C - variable argument function example, subset of printf() */
/* Released to public domain by author, David Harmon, Oct 1993 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void va_example(char *format, ...)
{
va_list ap;
char ch;

va_start(ap, format);

/* Note: because of default promotions, you can't use char,
or float types with va_arg. Use int or double instead. */

while ((ch = *format++) != 0) {
if (ch != '%')
fputc(ch, stdout);
else {
if ((ch = *format++) == 0)
break;
switch (ch) {
case 'd': {
int arg = va_arg(ap, int);
char buf[10];
itoa( arg, buf, 10);
fputs( buf, stdout);
break;
}

case 'c': {
int arg = va_arg(ap, int);
fputc( (char)arg, stdout);
break;
}

case 's': {
char *arg = va_arg(ap, char *);
fputs(arg, stdout);
break;
}

default:
fputc('%', stdout);
fputc(ch, stdout);
}
}
}
va_end(ap);
}
int main(void)
{
va_example("\"% s\" is a string, %c is a char, and %d is an integer.\n",
"Who is John Galt?", '$', -1);
return 0;
}

Jul 22 '05 #3
* tings:

How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?


Don't. Use the type-safe idiom exemplified by std::cout. I.e., member
functions or operators that return a reference to the object they're
called on, so that you can tack on further calls.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #4
"tings" <ti******@hotma il.com> wrote in message
news:%ofEd.9020 6$uM5.33520@bgt nsc05-
How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?


In standard C++, the preferred way to do this would be to:

(1) Create an abstract base class Variable with virtual functions, derived
class Int and so on from it, create a std::vector<Var iable*> though
std::vector<boo st::shared_ptr< Variable> > might be better in terms of memory
management.

(2) Create a std::vector<boo st::any>.

If all your types are fundamental types, then you can use the va_start,
va_arg, and va_end macros. Furthermore, if you want to pass a ... list
another function, you can pass the va_list to it. I think it's like this:

void myprintf(const char * format, ...) {
std::cout << "In my printf\n";
va_list ap;
va_start(ap, format);
vprintf(format, va_list);
va_end(ap);
}
Jul 22 '05 #5
"David Harmon" <so****@netcom. com> wrote in message
void va_example(char *format, ...)
{
va_list ap;
char ch;

va_start(ap, format);

/* Note: because of default promotions, you can't use char,
or float types with va_arg. Use int or double instead. */

while ((ch = *format++) != 0) {
if (ch != '%')
fputc(ch, stdout);
else {
if ((ch = *format++) == 0)
break;
switch (ch) {
case 'd': {
int arg = va_arg(ap, int);
char buf[10];
itoa( arg, buf, 10);
fputs( buf, stdout);
break;
}


Out of curiosity, can one use this method to pass class types? In other
words, is

MyClass arg = va_arg(ap, MyClass);

ok?
Jul 22 '05 #6
[ ... ]
Out of curiosity, can one use this method to pass class types? In other words, is

MyClass arg = va_arg(ap, MyClass);

ok ?


When you're passing a parameter as part of a variable parameter list,
"If the argument has a non-POD class type (clause 9), the behavior is
undefined." ($5.2.2/7).

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2006
by: Bob Murdoch | last post by:
I have a situation where I call a COM object from ASP that is supposed to create a file. On occasion, especially during development, the output of the COM function is an error string rather than the file name. I'd like to display this error string, regardless of it's contents. Right now, depending on the error string, I get an error message about missing a semicolon or some such. I've tried using Encode and Server.HTMLEncode with no...
9
6359
by: James Marshall | last post by:
I'm writing a library where I want to override document.write(), but for all document objects; thus, I want to put it in the prototype. I tried Document.prototype.write= my_doc_write ; but it didn't work. I discovered that this seemed to work: HTMLDocument.prototype.write= my_doc_write ; Why does HTMLDocument work here but not Document? Will this second
2
3547
by: Geoff Wilkins | last post by:
I am using <SCRIPT src=...> to import a Javascript routine from a remote source. I am then using some of the variables given values in the routine, in my own Javascript.. Unfortunately the routine also outputs to the page using document.write. I don't want this output. Any ideas how I can get rid of it? -- Best wishes,
14
4129
by: Eli | last post by:
I've got a script that I'm trying to debug which uses document.write() to place HTML within a page. In both IE6 and Firefox when I view source, I see only the script itself and not any HTML as it's being written into the page. Is there a way that I can view what is being placed into the page, instead of, or in addition to the javascript code?
2
2935
by: Eric Mitchell | last post by:
Hello all, I am using the document.write() method to create new content on the same page, however... I need to create a new button using this method (button in HTML). Complicating the matter worse, I have a javascript function that needs to be called in the onClick event of the button. Is there any way of doing this? Here is my code, which gives me an error because the function is read as an object, and there is no object... <script...
2
5781
by: bissatch | last post by:
Hi, I am trying to use JavaScript to write a table column on a web page. The code is as follows: <html> <head> <script> function displaycount() {
18
3713
by: jacob navia | last post by:
In C, we have read-only memory (const), read/write memory (normal data), and write only memory. Let's look at the third one in more detail. Write only memory is a piece of RAM that can only be written to, since its contents are undefined. The program is allocating a new piece of data, and the previous contents aren't relevant. This memory
88
8092
by: Peter Olcott | last post by:
Cab you write code directly in the Common Intermediate language? I need to optimize a critical real-time function.
1
3531
by: Tony B | last post by:
Hi, I'm trying to understand a small cpp program which uses a function called write. An example of a line using this function is write (hsocket,strclose,strlen(strclose)); where strclose is a string to write, and hsocket is a int containing a socket handle. The cpp program headers are #include <iostream> #include <string.h> #include <sys/stat.h>
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9483
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10346
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.