我可以使用 scanf 来捕获宽度由变量指定的指令吗? [英] Can I use scanf to capture a directive with a width specified by a variable?

查看:32
本文介绍了我可以使用 scanf 来捕获宽度由变量指定的指令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

其中 X 和 Y 应该是整数.问题是 X 和 Y 的值是编译时常量,即使我想将这些值硬编码到格式字符串中,我也不能,因为我不知道这些值.在 printf 中,您可以发送一个宽度变量以及带有%*s"的参数.有没有类似于 scanf 的东西?

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?

澄清一下,常量在编译时是已知的,但在编码时是已知的,而且我根本不知道.它们可能因平台或实现而异,并且在我完成后可能会发生变化.即使他们没有,我仍然不想在格式字符串中复制缓冲区大小,准备在我忘记保持同步的那一刻进行段错误.

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.

推荐答案

您可以使用 sprintf() 生成格式字符串:

You may produce the format string with sprintf():

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

太棒了,但以下 gcc 代码正在运行:

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

这篇关于我可以使用 scanf 来捕获宽度由变量指定的指令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆