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

时间:2011-10-11 23:22:19

标签: 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);

1 个答案:

答案 0 :(得分:6)

在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);