对齐来自用户输入的一行文本 (C++)

问题描述

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string line;
    const int SIZE = 75;
    int punct_index = 0;
    int whitespace_index = 0;
    
    cout << "Input Line: " << endl;

    getline(cin,line);

    while (line.find_first_of(".,!?;",punct_index) != string::npos)
    {
        punct_index = line.find_first_of(".,punct_index);
        line.insert(punct_index + 1," ");
        punct_index++;
    }

    while (line.size() < SIZE)
    {
        int rand_index = (rand() % SIZE) + 1;
        whitespace_index = line.find(" ",rand_index);
        if (whitespace_index != line.size() - 1)
        {
            line.insert(whitespace_index + 1," ");
        }
    }
    cout << "Your line justified is: "<< endl;
    cout << line << endl;

}

我在处理上面提供的代码中的间距时遇到了一些问题。
这是我给出的提示输出

Input Line:
Contrary to popular belief,Lorem Ipsum is not simply random text.
Your line justified is:
Contrary  to popular  belief,Lorem  Ipsum is   not  simply random text.

它应该是什么样子

Input Line:
Contrary to popular belief,Lorem Ipsum is not simply random text.
Your line justified is:
Contrary to  popular belief,Lorem Ipsum  is not   simply  random    text.

我想要做的是在标点符号后放置一 (1) 个空格以获得值 75(该行中应该有多少个字符),然后在同一行到达 75。

间距有点偏,但是调试的时候不知道哪里出错了。我注意到的第一件事是空格的第一个实例在正确的版本中被跳过,但我的版本注意到了。所以我自然会想“哦,我必须在某处创建一个变量 -1 或者只是减少 whitespace_index。”没有一个工作,所以我很困惑。我去看了我的教授向我们展示的内容,他的第二个 while 循环使用了 line.size() > SIZE。当我使用它时,整个代码块被完全跳过。
它的样子:

Input Line:
Contrary to popular belief,Lorem Ipsum is not simply random text.
Your line justified is:
Contrary to popular belief,Lorem Ipsum is not simply random text. 

注意行尾(句点之后)的额外空格。 老实说,我不知道出了什么问题,但我已经尝试调试代码以查看,但我不知道代码决定在哪里做与我需要的非常接近的事情。任何人都可以解释我做错了什么,因为这似乎是一个非常简单的修复,我想我只是忽略了它。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)