我想隨機添加一個字符串中的空格,直到總共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
在調試器中逐行執行代碼。原因應該變得明顯。 –
你爲什麼使用隨機數字?我的理解是,理由取決於行中的單詞和行的寬度,不需要隨機數字。 –
我正在使用一個隨機數,因爲我不需要將空間均勻分佈,所以隨機性似乎是下一個最佳選擇。 – Inert