2017-02-28 109 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; 
}