Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - Can I use scanf to capture a directive with a width specified by a variable?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'
", str1, str2 );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...