2017-02-28 65 views
-3

我試圖製作一個程序,它可以隨機生成一串字母,但當它生成一個用戶輸入的單詞時停止。如何查找隨機生成的字母串中的單詞?

我已經使它生成了字母,但我不知道如何使它從中識別出一個字。

for (int i = 1; i < 1000; i++) { 

    int n = rand() % 26; 
    char c = (char)(n + 65); 
    cout << c; 

} 
return 0; 

當我知道如何讓它找到用戶輸入時,我會將for循環更改爲while循環。

我對編程非常陌生,所以解決方案很可能很明顯。

+1

我希望通過「停止當這個詞產生」你的意思是說,它會停止後,每個字母在生成。否則你不會有太大的成功 – RSon1234

+0

這是一個棘手的問題,因爲「編程非常新」可能意味着很多事情。你熟悉'std :: string'嗎?如果你知道的話,這將是這個難題的一部分。你是否注意到性能(程序運行速度)?這些微不足道的解決方案的運行時間性能很差,這可能無關緊要,但對於您編寫的未來程序可能很重要(不想讓壞習慣!) –

+0

如果繼續生成字母,最終會生成一個真正的單詞,最終與用戶輸入相匹配。 – Dankanism

回答

0

正如其中的意見建議,你需要從你的字符創建一個字符串。在那之後,我會建議看:

http://www.cplusplus.com/reference/string/string/find/

其搜索功能的其他琴絃使用的字符串...這是你在尋找什麼。

其中一個評論還建議使用==來比較從chars和用戶輸入字符串中創建的字符串,但是當字符串:: find函數完全相同時沒有太多的用法但更有效的

0

一個現代的C++解決方案。 下面是主要功能中有趣的部分。

#include <random> 
#include <iostream> 
#include <algorithm> 
#include <list> 
#include <sstream> 

void NotFoundMessage(std::list<char>& randomSequence); 
void FoundMessage(long long iterationCount); 

// Seed with a real random value, if available 
std::random_device r; 
std::default_random_engine e1(r());  
// A random character between 'A' and 'Z' 
std::uniform_int_distribution<int> uniform_dist('A', 'Z'); 

char nextRandomCharacter() 
{ 
    return static_cast<char>(uniform_dist(e1)); 
} 

int main() 
{ 
    std::string input; 
    std::cin >> input; 

    // <--- NEEDS CHECKS IF INPUT IS CORRECT!!!! 

    std::list<char> randomSequence; 

    // Fill randomSequence with initial data 
    for (const auto& c : input) 
    { 
     randomSequence.push_back(nextRandomCharacter()); 
    } 

    long long iterationCount = 1; 

    while (!std::equal(input.begin(), input.end(), 
         randomSequence.begin())) 
    { 
     NotFoundMessage(randomSequence); 

     // remove character from front and add random char at end. 
     randomSequence.pop_front(); 
     randomSequence.push_back(nextRandomCharacter()); 

     iterationCount++; 
    } 

    FoundMessage(iterationCount); 
} 

void NotFoundMessage(std::list<char>& randomSequence) 
{ 
    std::cout << "Not found in: "; 
    for (const auto& c : randomSequence) 
     std::cout << c << ' '; 
    std::cout << '\n'; 
} 

void FoundMessage(long long iterationCount) 
{ 
    std::cout << "Found after " 
      << iterationCount 
      << " iterations." 
      << std::endl; 
}