Betamoo
Betamoo

Reputation: 15960

#define usage in C/C++

I need to write such a define in C/C++

#define scanf( fscanf(inf,

in order to replace each scanf( with fscanf(inf, literary

But I do not know how...

Thanks

Upvotes: 6

Views: 2417

Answers (5)

VeeArr
VeeArr

Reputation: 6188

You want to use a Variadic macro.

In your case, I believe you want:

#define scanf(...) fscanf(inf,__VA_ARGS__)

Upvotes: 12

fredoverflow
fredoverflow

Reputation: 263350

I need to write such a define in C++

No, you don't. What you really want to do is redirect stdin.

freopen(inf, "r", stdin);

Upvotes: 5

ShinTakezou
ShinTakezou

Reputation: 9681

not possible the way you tried of course.

you have to do things like

#define scanf(S, ...) fscanf(inf, S, __VA_ARGS__)

See e.g. here

EDIT: GNU cpp supports variadic macros too; it is VA_ARGS preceded by double underscore and ended with double underscore... I have to study escaping markup here...

Upvotes: 1

Thomas Dignan
Thomas Dignan

Reputation: 7102

Just write all your code using fscanf, and define the file name with a macro like this:

#ifdef USE_SCANF
#define SCANF_FILE(file) stdin
#else
#define SCANF_FILE(file) file
#endif

fscanf(SCANF_FILE(blah), "%d", &a);

Upvotes: 3

Peter Ruderman
Peter Ruderman

Reputation: 12485

You can't replace a parenthesis. If you're using Visual C++, then you can use a variadic macro to accomplish what you want:

#define scanf( format, ... ) fscanf( inf, format, __VA_ARGS__ )

Other compilers may have a similar facility, but I'm not familiar with them.

Upvotes: 0

Related Questions