(C++) 如何在控制台行末尾不打断单词的情况下打印长消息?

(C++) How can I print a long message without breaking words at the end of a console line?

这在技术上是两件事,但它们本质上是一样的,所以我将它们合并为一个问题。

我想打印长消息而不必控制文本中的换行符。比如我写了一个很长的字符串,用std::cout << str << std::endl;打印出来。 此处添加的管道 | 用于演示目的,以当前 window 大小显示控制台行的结尾,以及一个 @ 标志以显示文本停止打印的位置在管道的尽头。

$ ./text_test
This sentence is so long that the word 'developer' splits into two, and the deve|
loper has no clue how this placeholder sentence was a good idea at the time.@   |
$

我希望此示例文本打印出来的样子是这样的:

$ ./text_test
This sentence is so long that the word 'developer' splits into two, and the@    |
developer has no clue how this placeholder sentence was a good idea at the time.|
$

在第一行末尾的'the'之后也不应该有space,因为在正确的句子中,space会溢出到下一行,因为此示例所示,其代码位于输出下方:

$ ./long_test
You are lost in the forest and you have nothing on you. How did you end up here?|
 Questions can be answered later; looks like trouble is on its way! Prepare for |
battle! @
$
// here ^ notice how there is a space after the ! sign, when there shouldn't be,
// and also notice the improper space before "Questions".
// The second line should have also ended with 'r', not ' ', as I've marked by
// the lack of an @ sign after "for".
// Source code:

#include <iostream>
#include <string>
#include <sstream>

void lprint (std::string str) {
  std::istringstream ss;
  std::string unit;
  while (ss >> unit) {
    std::cout << unit << " ";
  }
}

int main() {
  std::string str " /* long message */ ";
  std::cout << str << std::endl;
  return 0;
}

我还想知道(如果这与我已经提出的问题相互排斥)如何检测屏幕上一行的结尾,也许是通过可以显示的文本列数(像 80 等)。非常感谢。

你可以使用像

这样的函数
void OutputText(std::string s)
{
    int bufferWidth = GetBufferWidth();
 
    for (unsigned int i = 1; i <= s.length() ; i++)
    {
        char c = s[i-1];
 
        int spaceCount = 0;
 
        // Add whitespace if newline detected.
        if (c == ‘n’)
        {
            int charNumOnLine = ((i) % bufferWidth);
            spaceCount = bufferWidth – charNumOnLine;
            s.insert((i-1), (spaceCount), ‘ ‘);
            i+=(spaceCount);
            continue;
        }
 
        if ((i % bufferWidth) == 0)
        {
            if (c != ‘ ‘)
            {
                for (int j = (i-1); j > -1 ; j–)
                {
                    if (s[j] == ‘ ‘)
                    {
                        s.insert(j, spaceCount, ‘ ‘);
                        break;
                    }
                    else spaceCount++;
                }
            }
        }
    }
 
    // Output string to console
    std::cout << s << std::endl;
 }

this website 上有进一步的解释。