我的教授要求我的代码每行不超过 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/