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

问题描述

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

我想打印长消息而不必控制文本中换行的位置。比如我写了一个长字符串,用<uses-permission android:name="android.permission.BIND_TELECOM_CONNECTION_SERVICE"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.RECORD_AUdio" /> <application>.... <service android:name="myAPPID.VoiceConnectionService" android:label="MY APP NAME" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"> <intent-filter> <action android:name="android.telecom.ConnectionService" /> </intent-filter> </service> 打印出来。 管道 std::cout << str << std::endl; 在此处添加用于演示目的,以当前窗口大小显示控制台行的末尾,以及 | 符号以显示文本不在管道的末尾时停止打印的位置

@

我希望这个示例文本看起来像打印的:

$ ./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.@   |
$

在第一行末尾的“the”之后也不应该有空格,因为对于正确的句子,空格会溢出到下一行,如本例所示,其代码位于输出

$ ./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.|
$

我还想知道(如果这与我已经询问的内容相互排斥)如何检测屏幕上一行的结尾,也许是通过可以显示的文本列数(例如 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 中有进一步的解释。