繁体   English   中英

(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 大小的控制台行的末尾,以及一个@符号以显示文本停止打印的位置,而不是 pipe 所在的末尾。

$ ./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”之后也不应有空格,因为使用正确的句子,空格会溢出到下一行,如本例所示,其代码位于 output 下方:

$ ./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 等) . 非常感谢。

您可以使用 function 之类的

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;
 }

本网站对此作了进一步的解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM