我有一个字符数组,该数组会生成一个随机的小写字母数组,该数组由用户输入。我的问题是,在生成随机字母数组之后,用户输入一对字符(两个字母),我的代码应检查该对是否在所生成的随机数组中。当它只检查一个字母时它工作正常,但是当我介绍第二个字母时它不起作用。我将不胜感激。
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}
答案 0 :(得分:0)
首先,您不存储随机生成的字符
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
这只是在ch中写入一个随机字符,并在每次迭代时将其显示在控制台上。您无需存储数据,ch只会包含循环结束后的最后一个随机字符,其他所有内容都会丢失。
您要搜索的部分是双重错误。
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";