【问题标题】:Is it ok to use non printable character as empty char in C可以在C中使用不可打印字符作为空字符吗
【发布时间】:2021-04-09 09:34:01
【问题描述】:

我想在 C 中使用 printf 打印字符或什么都不打印。

假设我有这个结构,其中 index 是可打印字符或 6(不可打印字符)。

struct indexed {
    char name;
    char index;
};

struct indexed item = { 'x', 6 };

printf("Indexed char '%c%c' is worth printing", item.name, item.index);

这将导致打印“x”而没有任何空格。但是这种方式看起来很hacky,所以......

这样在 C 中使用不可打印字符是否可以,如果可以,哪个最好?

我真的不想将 printf 与 if 语句分开,也不想在第一个字符后面有额外的空间。

【问题讨论】:

  • 我不会推荐它。如果您不想打印字符,请不要打印它。对我来说,这看起来像 XY Problem
  • 取决于操作系统,这可能会导致奇怪的副作用。 ;) 所以不行。我不会推荐它。可以打印一个字符的字符串,也可以打印一个空字符串,效果相同但可靠。
  • 这个想法更像是:它们不是可打印的字符,其中一些已经过时了,所以为什么不这样使用它们。感谢您的cmets,我将创建并接受答案

标签: c printf


【解决方案1】:

就像在 cmets 中所说的那样,如果您不想使用 if 语句或空格,则更可靠的解决方案是像这样使用 '\0':

struct indexed {
    char name;
    char index;
};

struct indexed item = { 'x', '\0' };

char temp[] = { item.name, item.index, '\0' };
printf("Indexed char '%s' is worth printing", temp);

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多