2015-05-05 16 views
-3

我的源代碼,我不能混淆我的話,它讓我得到任何我不想要的東西。C++不能混淆一個詞

我沒有錯誤,沒有警告,但舉個例子,如果我說:爸爸,它給我'P A',爲什麼? 感謝您的幫助!

#include <iostream> 
#include <string> 
#include <random> 
#include <chrono> 

using namespace std; 

string melangeLettre(string mot); 
int main() 
{ 
    cout << "Saisissez un mot mystere: \n> "; 
    string motMystere{}; 
    cin >> motMystere; 

    cout << "Quel est ce mot ? \n"; 
    string const newMot = melangeLettre(motMystere); 
    cout << newMot << endl; 

    return {0}; 
} 

string melangeLettre(string mot) 
{ 
    size_t random = chrono::system_clock::now().time_since_epoch().count(); 
    mt19937 gen{random}; 
    string newMot{}; 

    for (unsigned int i{}; i < mot.size(); ++i) 
    { 
     uniform_int_distribution<> getNbr(0, mot.size()); 
     newMot.push_back(mot[getNbr(gen)]); 
     mot.erase(i, 1); 
    } 

    return newMot; 
} 
+0

更願意通過'常量的std :: string'傳遞字符串,這樣編譯器並不需要進行復印。 –

+0

如果你的目標只是將字符串洗牌,那麼使用'std :: shuffle'有什麼問題? – PaulMcKenzie

回答

2

您在代碼中有幾個問題。您choosen分佈:

uniform_int_distribution<> getNbr(0, mot.size()); 

可以導致包括mot.size()這是過去的字符串的結尾數字。非空字符串中的最後一個字符的索引爲mot.size()-1

在此代碼:

newMot.push_back(mot[getNbr(gen)]); 
mot.erase(i, 1); 

你的字符複製到新的單詞,然後刪除原字不同的字符(也可能是相同的字符,但只有一個偶然的機會)。你可能想要刪除您添加到新詞,如相同的字符:

auto j = getNbr(gen); 
newMot.push_back(mot[j]); 
mot.erase(j, 1); 

你的循環迭代過幾次,因爲你在每個循環的字刪除字符。正因爲如此,你真的只需要迭代,直到你的原始單詞是空的。

這三樣東西改變循環在你的函數:

while (mot.size() > 0) 
{ 
    uniform_int_distribution<> getNbr(0, mot.size()-1); 
    auto j = getNbr(gen); 
    newMot.push_back(mot[j]); 
    mot.erase(j, 1); 
}