tags:

views:

131

answers:

3

I have the following code:

scanf(" %Xs %Ys", buf1, buf2);

Where X and Y should be integers. The problem is that the values for X and Y are compile-time constants, and even if I wanted to hard-code the values into the format string, I can't, because I don't know the values. In printf, you can send a width variable along with the arguments with "%*s". Is there anything analogous for scanf?

EDIT: To clarify, constants are known at compile time, but not at coding time, and not by me at all. They may vary by platform or implementation, and they may change after I'm done. Even did they not, I still wouldn't want to have buffer sizes duplicated in format strings, ready to segfault the minute I forget to keep them synchronized.

+4  A: 

The problem is that the values for X and Y are compile-time constants

Then use macro paste feature:

#include <stdio.h>

#define TEST 2

#define CONST_TO_STRING_(x) #x
#define CONST_TO_STRING(x) CONST_TO_STRING_(x)

int main() {
 printf("1 " CONST_TO_STRING(TEST) " 3\n");
 return 0;
}
LiraNuna
This won't work if the compile-time constants are defined as something other than a simple unadorned integer, for example `sizeof foo`, `10 * 2`, `500UL`, `0x20` and `'\n'` will all fail.
caf
OP didn't say how those constants are declared. If this is not his/her case, the question should be edited.
LiraNuna
The OP said they were "compile-time constants", a term which encompasses all of the constants in my examples.
caf
+5  A: 
sambowry
Waste of runtime resources if the numbers are constants, don't you think?
LiraNuna
It is true, but more flexible. It is working when X and Y read from a file, etc.
sambowry
Jonathan Leffler
I think you need to change `LIST param` to `LIST(param)` - any compiler accepting the first form is wrong and needs fixing.
Chris Lutz
@Chris: the 'param' contains the necessary parenthesis. [ 'LIST param' --> 'LIST (X,Y)' --> 'X,Y' ]
sambowry
A: 

Your question is not clear. If you don't know the values, then they are probably run-time constants, not compile-time constants.

If that's the case (i.e. they are run-time consants), then no, there's no such feature in 'scanf'. The only thing you can do is to produce the complete format string (with the concrete values embedded in it) at run-time by using 'sprintf' and then pass that format string to your 'scanf'.

AndreyT
There can easily be unknown compile-time constants - ever heard of `#ifdef` ?
Chris Lutz
Well, when I say "unknown", I mean "unknown to the compiler at the time of compilation", becaus in my opinion this is the only relevant form of "unknown". '#define'd manifest constants known at the time of compilation can be embedded into the format string by the preprocessor (already answered here).
AndreyT