c++ - 如何在 C++ 代码中将我的 printf 语句限制为每行 80 个字符?

标签 c++ printf

我的教授要求我的代码每行不超过 80 个字符,但我有一些 printf 语句超过了这个限制。有没有办法在不更改输出的情况下将此语句分成两行或更多行?

请求示例:

printf("\n%-20s %-4d %-20s %-4d %-20s %-4d\n%-20s %-4d %-20s %-4d%-20s %-4d\n%-20s %-4d %-20s %-4d %-20s %-4d\n%-20s %-4d %-20s %-4d %-20s %-4d\n%-20s %-4d %-20s %-4d\n", "1 - Ones", ones, "2 - Twos", twos, "3 - Threes", threes, "4 - Fours", fours, "5 - Fives", fives, "6 - Sixes", sixes, "7 - Three of a Kind", threeOfAKind, "8 - Four of a Kind", fourOfAKind, "9 - Full House", fullHouse, "10 - Small Straight", smallStraight, "11 - Large Straight", largeStraight, "12 - Yahtzee", yahtzee, "13 - Chance", chance, "Total Score: ", score);

最佳答案

在 C++ 中,您可以像这样拆分文字字符串:

printf("This is a very long line. It has two sentences.\n");

进入

printf("This is a very long line. "
       "It has two sentences.\n");

任何仅由空格分隔的双引号字符串,在解析之前由编译器合并为一个字符串。生成的字符串不包含任何额外的字符,除了每对双引号之间的字符(因此,没有嵌入换行符)。

对于您帖子中包含的示例,我可能会执行以下操作:

printf("\n%-20s %-4d %-20s %-4d %-20s %-4d\n"
       "%-20s %-4d %-20s %-4d%-20s %-4d\n"
       "%-20s %-4d %-20s %-4d %-20s %-4d\n"
       "%-20s %-4d %-20s %-4d %-20s %-4d\n"
       "%-20s %-4d %-20s %-4d\n",
       "1 - Ones", ones, "2 - Twos", twos, "3 - Threes", threes,
       "4 - Fours", fours, "5 - Fives", fives, "6 - Sixes", sixes,
       "7 - Three of a Kind", threeOfAKind,
           "8 - Four of a Kind", fourOfAKind,
           "9 - Full House", fullHouse,
       "10 - Small Straight", smallStraight,
           "11 - Large Straight", largeStraight,
           "12 - Yahtzee", yahtzee,
       "13 - Chance", chance, "Total Score: ", score);

关于c++ - 如何在 C++ 代码中将我的 printf 语句限制为每行 80 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733667/

相关文章:

c++ - 创建子进程

c++ - constexpr if 和返回值优化

c++ - 错误 c2872 Visual Studio 2013

在一个字符中连接一个包含可变大小数据的结构*

c++ - 为什么右值引用参数更喜欢 const 左值引用而不是右值引用参数?

c++ - 使用互斥锁在 C++ 中复制构造函数

windows - 如何在 x86_64 程序集中使用 printf 和 scanf?

c - sprintf 的意外行为

c - printf scanf 执行顺序正在交换

java - 如何在 Java 中打印带有 2 位小数的 float ?