Sign in to follow this  

(C++) Passing ... as an argument.

This topic is 3864 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've hit a bit of a snag. I have a function which takes ... as a parameter, and I want to pass the ... to another function. However, I can't seem to find any way to do this. I've tried just leaving it as ..., I've tried using macros to redirect the function to the proper call, but I can't just seem to figure it out. I'm trying currently: #define bscanf(x,y,...) sscanf(Test,y,...) With test as just a string. I try calling: char Test[] = "Random Words 1."; int K; bscanf(99,"%*s %*s %d",&K); Now, when I try and compile with the G++, I get: expected primary-expression before '...' token . I just can't figure out what to do. Anyways to resolve this? Thanks in advance, Erondial

Share this post


Link to post
Share on other sites
You need to remember that the preprocessor is not much more than a stupid search-and-replace engine. It does not know about variadic functions. Your define doesn't really mean anything to the preprocessor.

Now, the answer to your question depends on this: are you programming in C, or C++?

If C, then you will probably need to define your own variadic function, and forward the parameters to sscanf. I can't really tell you how to do it, since I don't know C or its constructs very well.

If C++, then forget scanf, and start using C++ streams (notably operator>> overloads). More generally, C++ commonly uses method chaining where a variadic function might have been.


jfl.

Share this post


Link to post
Share on other sites
Let me give you an example of how it would work with streams:

struct Foo {
std::string s1;
std::string s2;
int i;

friend std::istream & operator>>( std::istream & in, Foo & f ) {
return in >> std::ws >> f.s1 >> std::ws >> f.s2 >> f.i;
}
};



And usage is like:

std::stringstream Test( "Random Words 1." );
Foo f;
Test >> f;


And the nice thing is that you can use this with anything that derives from istream, such as an ifstream or cin (you could make it more general with templates).


jfl.

Share this post


Link to post
Share on other sites

This topic is 3864 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this