Can I use scanf to capture a directive with a widt

2019-01-27 02:57发布

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.

标签: c scanf
3条回答
狗以群分
2楼-- · 2019-01-27 03:13

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;
}
查看更多
走好不送
3楼-- · 2019-01-27 03:20

You may produce the format string with sprintf():

sprintf( format, " %%%is %%%is", X, Y );
scanf(format, buf1, buf2);

EDIT: amazing, but the following gcc code is working:

#include <stdio.h> 

#define LIST(...) __VA_ARGS__ 

#define scanf_param( fmt, param, str, args ) {  \ 
  char fmt2[100]; \ 
  sprintf( fmt2, fmt, LIST param ); \ 
  sscanf( str, fmt2, LIST args  ); \ 
} 

enum { X=3 };
#define Y X+1 

int main(){
  char str1[10], str2[10];

  scanf_param( " %%%is %%%is", (X,Y), " 123 4567", (&str1, &str2) );

  printf("str1: '%s'   str2: '%s'\n", str1, str2 );
}
查看更多
放荡不羁爱自由
4楼-- · 2019-01-27 03:25

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

查看更多
登录 后发表回答