scanf() 的宽度说明符 - 要使用的字符长度在编译时不固定,仅在运行时确定。怎么让它变呢?

Rob*_*rtS 3 c c++ runtime scanf format-specifiers

我想将字段宽度说明符应用于 scanf() 操作以读取字符串,因为明确指定要读取/使用的字符数量,并且不会使 -scanf()操作容易导致缓冲区溢出。除了目标参数指向一个已经匹配的char数组,该数组与元素的大小完全相同,字段宽度的所需值必须是,+ 1 表示\0. 这个char数组的大小也是在运行时之前确定的。

现在的问题是最大字段宽度的值无法固定;它仅在运行时确定。

我如何实现,能够在运行时确定最大字段宽度的值?


我做了一些研究,发现在 Stackoverflow 上已经有一个问题,在它的来源中,解决了与我完全相同的问题。scanf() 可变长度说明符

但不幸的是,在问题的发展以及答案的内部,解决方案只能使用预处理器指令宏处理,这意味着字段宽度的值实际上并不是那个变量,它在编译时是固定的-时间。


我有一个例子给你我的意思:

#include <stdio.h>

int main(void)
{
    int nr_of_elements;

    printf("How many characters your input string has?\n");
    scanf("%d",&nr_of_elements);

    nr_of_elements++;                          //+1 element for the NULL-terminator.

    char array[nr_of_elements];

    printf("Please input your string (without withspace characters): ");
    scanf("%s",array);        // <--- Here i want to use a field width specifier.      

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想做的是这样的:

scanf("%(nr_of_elements)s");
Run Code Online (Sandbox Code Playgroud)

或者,如果我遵循链接问题中答案的编程风格:

scanf("%" "nr_of_elements" "s");
Run Code Online (Sandbox Code Playgroud)
  1. 有没有办法使scanf()-function内的最大字段宽度取决于由运行时确定或生成的值?

  2. 有没有替代方法可以实现相同的目标?

我使用 C 和 C++ 并为两者标记问题,因为我不想为每个分开的问题重复相同的问题。如果这些之间的答案发生变化,请说明重点是哪种语言。

Roy*_*dan 6

您可以使用sprintf它作为一种格式:

只是为了评论,我使用了unsigned因为我无法想象字符串长度为负的情况。

#include <stdio.h>

int main(void)
{
    unsigned nr_of_elements;

    printf("How many characters your input string has?\n");
    scanf("%u",&nr_of_elements);

    nr_of_elements++;                          //+1 element for the NULL-terminator.

    char array[nr_of_elements];

    printf("Please input your string (without withspace characters): ");

    char format[15]; //should be enough
    sprintf(format, "%%%us", nr_of_elements - 1);
    scanf(format,array);       

    return 0;
}
Run Code Online (Sandbox Code Playgroud)