【问题标题】:Width Specifier for scanf() - Length of characters to consume is not fixed at compilation and only determined at run-time. How to make it variable?scanf() 的宽度说明符 - 要使用的字符长度在编译时不固定,仅在运行时确定。如何使其可变?
【发布时间】:2020-03-28 02:53:21
【问题描述】:

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

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

如何在运行时确定最大字段宽度的值?


我做了一些研究,发现在 Stackoverflow 上已经提出了一个问题,在其来源中,解决了与我完全相同的问题。 scanf() variable length specifier

但不幸的是,在问题的发展中以及在答案中,解决方案原来只使用预处理器指令宏处理,这意味着字段宽度的值实际上不是那个变量,它是在编译时修复。


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

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

我想做的是这样的:

scanf("%(nr_of_elements)s");

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

scanf("%" "nr_of_elements" "s");

  1. 有没有办法让 scanf() 函数内部的最大字段宽度取决于运行时确定或生成的值?

  2. 有没有其他方法可以达到同样的效果?

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

【问题讨论】:

  • @SanderDeDycker 是的,我做到了。我没有发现任何东西可以使最大字段宽度变量 = 使其在运行时受到变量值的影响。你有参考吗?那太好了。
  • 道歉 - 我误读了你的问题。
  • char array[nr_of_elements]; 是 VLA,因此在 C++ 中无效。
  • @mch 我很确定这仍然可以在 GCC 中编译,但它的编码很糟糕

标签: c++ c runtime scanf format-specifiers


【解决方案1】:

你可以使用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;
}

【讨论】:

  • @רועיאבידן 这是一个非常棘手的方法。我没想过要在外部构建格式字符串。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 2011-06-15
  • 2020-02-05
  • 2011-10-20
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
相关资源
最近更新 更多