tags:

views:

218

answers:

5

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

+12  A: 

You want to use a Variadic macro.

In your case, I believe you want:

#define scanf(...) fscanf(inf,__VA_ARGS__)
VeeArr
Note that this is not portable.
Brian Neal
This could work.
Tom Dignan
@Brian: it's in the C++0x draft and supported by GNU, Intel and Microsoft, so at least on x86 I'd consider it portable enough for most purposes
Christoph
It's in the C99 official standard, so it is portable C.
caf
The question was originally for just C++, later edited to both C/C++. For those of us who use more compilers than the mainstream, and we want our code to be portable now, this isn't an option. Sure, go ahead and use it if all your target compilers support it. I still think it is worth mentioning that it isn't portable for C++ right now. But yes, it is in the C++0x draft standard.
Brian Neal
spelling: it's variadic, not variadric :)
Jordan Lewis
Fixed it, thanks.
VeeArr
A: 

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.

Peter Ruderman
It's standard C99. §6.10.3.1
Matthew Flaschen
Colour me surprised. Thanks for the clarification.
Peter Ruderman
C99 standard as far as I know.
ShinTakezou
The question was for C++, where this is not standard.
Brian Neal
@Brian: but it's in the C++0x draft, so it's reasonable to use it as long as it's supported by your compiler
Christoph
Unless you want your code to be portable now.
Brian Neal
gcc and microsoft's compilers have both the extention. Fastly reading forums, it seems Intel compiler has too someway. And wikipedia says Borland compiler too support them. So I suppose we can say all the main compilers have a preprocessor supporting variadic macro.
ShinTakezou
+1  A: 

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...

ShinTakezou
Surround text with backticks to create inline code. It's the best way to write `__VA_ARGS__` in the middle of a paragraph. ;)
Chris Lutz
+4  A: 

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);
Tom Dignan
+4  A: 

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);
FredOverflow