My professor requests that my code does not exceed 80 characters per line, but I have some printf statements that exceed this limit. Is there a way to break this statement into two or more lines without changing the output?
Example by request:
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);
You need to specify a precision (number after the dot '. ') in the %s format parameter to limit the size of the string printed. A precision field is a non-negative number that specifies the number of characters to print. Using this format string, the string passed by str will be truncated after five characters.
% indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.
You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string.
Only if the fgets() can terminate once its reached the max limit of characters. you can do this in scanf itself, scanf("%10s",Name);
In C++, you can break literal strings like this:
printf("This is a very long line. It has two sentences.\n");
into
printf("This is a very long line. "
"It has two sentences.\n");
Any double-quoted strings that are separated by only whitespace, are coalesced into one string by the compiler before parsing. The resulting string does not contain any extra characters except what is between each pair of double quotes (so, no embedded newline).
For the example included in your post, I might do the following:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With