我正在尝试在字符串中随机添加空格,直到字符串总共80个字符。出于某种原因,我的程序不起作用。我在这里错过了什么吗?它只在同一位置输入空格,而不是随机输入:/。
Input : My name is bob
OutPut: Debug Error! abort() has been called
我的输出如下:
// Schedule this to run periodically via ScheduledExecutorService
class ManualStarter {
private final AtomicBoolen isRunning = new AtomicBoolean(false);
private ExecutorService exec = Executors.newSingleThreadedExecutor();
public void run() {
if (!isRunning.getAndSet(true)) {
// It wasn't running so this will start it
exec.submit(new MainProcess(isRunning));
}
}
}
class MainProcess extends Runnable {
private final AtomicBoolean isRunning;
MainProcess(AtomicBoolean isRunning) { this.isRunning = isRunning; }
@Override
public void run() {
// do whatever it does
isRunning.set(false);
}
}
答案 0 :(得分:1)
首先,我真的很讨厌我无法发表评论的事实,除非我的声誉超过50;因此我的大部分意见都是假设。
你做错了什么
首先,你总是会在第一个(实际上是实现定义的)空间位置的同一位置安放空间。对于字符串"My name is Bob"
,其位置为2
。
其次,你的随机生成器对空间插入的位置没有贡献。
最后,您检查随机生成的数字是否在限制范围内的方法是不正确的。此语句random_number < 40 ? true : false;
没用,它根本不会贡献或更改代码的行为,并且可能会被编译器优化掉。您还应该注意,random_number < 40
完全相同,但代码污染较少。
固定代码
#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()
被视为有害。 Source