如何做文本校对

How to do text justification?

本文关键字:文本校对 何做      更新时间:2023-10-16

我试图在字符串中随机添加空格,直到字符串共有80个字符长。不知道为什么,我的程序出问题了。我遗漏了什么吗?它只在相同的位置输入空格,而不是随机输入:/。

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using std::cin; using std::cout; using std::string; using std::endl;
const int line_width = 80;
int main()
{
    //declare string and get user input
    string not_justified;
    cout << "Input a line of text less than 80 characters to be justfied: " << endl;
    getline(cin, not_justified);
    int position = not_justified.find(' ');
    //start random number generator
    srand(time(nullptr));
    while (not_justified.size() != line_width)
    {
        //find space position
        position = not_justified.find(' ');
        //get random number from 1-80
        int random_number = rand() % 80 + 1;
        //test to see if number is less than 40, if it is return true
        random_number < 40 ? true : false;
        //if true, insert a space
        if (true)
            not_justified.insert(position, " ");
        position += position;
    }
    cout << "Your justified line is: " << not_justified << endl;
} //end main

我的输出如下所示:

Input : My name is bob
OutPut: Debug Error! abort() has been called

首先,我真的很讨厌这样一个事实:除非我的声誉超过50,否则我无法发表评论;因此,我的大部分输入都是由假设组成的。

你做错了什么

首先,您总是将空间放置在相同的位置,即第一个(实际上是实现定义的)空间位置。对于弦,"My name is Bob"在位置2

其次,你的随机生成器对空格插入的位置没有贡献。

最后,你们检查随机生成的数字是否在限制范围内的方法是不正确的。这个语句random_number < 40 ? true : false;是无用的,它根本不贡献或改变你的代码的行为,并且很可能被编译器优化掉。您还应该注意到,random_number < 40做了完全相同的事情,但是代码污染更少。

<<p> 固定代码/strong>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <random> 
#include <vector>
using std::cin; using std::cout; using std::string; using std::endl;
const int line_width = 80;
std::vector<size_t> find_all_of( const std::string &str, const char &what = ' ' )
{
    auto count = 0u;
    std::vector<size_t> result;
    for ( auto &elem : str )
    {
        if ( elem == what )
            result.emplace_back( count );
        ++count;
    }
    return result;
}
int main( )
{
    //declare string and get user input
    string not_justified;
    cout << "Input a line of text less than 80 characters to be justfied: " << endl;
    getline( cin, not_justified );
    std::mt19937 rng{ std::random_device( )( ) }; // random number generator
    while ( not_justified.size( ) < line_width )
    {
        auto spaces = find_all_of( not_justified ); // find all of the current spaces
        std::uniform_int_distribution<size_t> distribution{ 0, spaces.size( ) - 1 }; // only allow results within the bounds of spaces
        auto where = spaces[distribution( rng )];  // select a random position using the distribution method
        not_justified.insert( where, " " ); // insert it.
    }
    cout << "Your justified line is: " << not_justified << endl;
    cin.get( );
} //end main

其他点

rand()被认为是有害的。源