【问题标题】:Extra whitespace in output after using scanf ( %c)使用 scanf ( %c) 后输出中的额外空格
【发布时间】:2013-01-14 17:29:39
【问题描述】:

在我第一次运行这个 do/while 循环后,输出似乎总是在 printf 之前有一个额外的空间。我认为这可能与缓冲区溢出有关,但我不太确定如何摆脱它。

任何帮助将不胜感激,谢谢!

do {
   printf("Enter a format specifier: ");
   scanf(" %c", fmt+1);
   printf(fmt, value);
} while(*(fmt+1) != 'q');

**fmt 是一个字符数组。

【问题讨论】:

    标签: whitespace scanf buffer-overflow


    【解决方案1】:

    我把你的代码扩展成一个完整的程序如下:

    #include "stdio.h"
    
    main () {
        char fmt[2] = "% ";
        int value = 23;
        do {
            printf("Enter a format specifier: ");
            scanf(" %c", fmt+1);
            printf(fmt,value);
        } while(*(fmt+1) != 'q');
    }
    

    ...并得到以下结果:

    Enter a format specifier: i
    23h (Enter a format specifier: d
    23h (Enter a format specifier: x
    17h (Enter a format specifier: o
    27h (Enter a format specifier: q
    qh (
    

    此输出与您似乎观察到的略有不同,但我认为原则上可能相同。如果是这样,我认为正如您所怀疑的那样:由于fmt 被声明为一个字符数组,该数组的长度不足以包含应位于任何 C 字符串末尾的空值,从而导致缓冲区溢出错误。因此,printf() 在格式字符之后继续写入随机数据,直到碰巧遇到一个空值。

    更改第四行代码以确保字符串有足够的空间容纳可见字符和终止的 null,但没有更多,即:

    char fmt[] = "% ";
    

    ... 给出以下结果(这可能与您预期的一样?):

    Enter a format specifier: i
    23Enter a format specifier: d
    23Enter a format specifier: x
    17Enter a format specifier: o
    27Enter a format specifier: q
    q
    

    有关此问题的更多信息,您可以阅读Char array initialization dilemma

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多