我想做什么:
生成仅包含字母a,b,c,d的随机字母序列。 让用户输入一个序列作为猜测,输出他有正确字母的位置,在错误的位置打印正确字母的数量,重复直到用户正确猜测序列或在10次错误尝试后正确猜测。
我的尝试:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main ()
{
char lettres[4] = {'a','b','c','d'};
char rString[5];
int i=0;
srand(time(0));
while(i<5)
{
int temp = rand() % 4;
rString[i] = lettres[temp]; //while loop to generate the random sequence and put it in rString
i++;
}
int u=0;
char t[5];
while(u<10)
{
cout << "Enter your guess ";
cin >> t[5]; // take guess attempt as an array, each letter at a different index
int k;
int compteur=0;
int t2[5];
int compteur2=0;
for(k=0; k<5; k++)
{
if(rString[k]==t[k])
{
k = t2[compteur2]; //if letter is at correct position put its index in a new array
compteur2++;
}
else
{
for(int j=0; j<5; j++)
{
if(t[k]==rString[j])
{
compteur++; //if not check if there is correct letters and count them
}
}
}
}
cout << compteur2 << " " << compteur;
if(compteur2==5)
{
cout<<"bravo";
i = 10; // if guessed sequence is correct set i=10 to exit
}
else
{
cout<< "Positions with correct letter: " << t2[5];
cout <<"You have a total of"<< compteur << "correct letters";
}
u++;
}
return 1;
}
当前输出:
Enter your guess: abcd //obviously I entered abcd
0 0Positions with correct letter: 32766You have a total of0 correct letters
//execution ends
更新:
我做了2处更改,建议其中一项。
首先,我更改了将猜测的序列放入数组的方式,现在如下:cin >> t;
而不是cin >> t[5];
其次,我意识到我通过写t2[5]
将整数放入k=t2[compteur2]
中,据我所知这是错误的,我将其更改为t2[compteur2]=k
然后,我开始使用循环来打印阵列。
现在程序不会立即终止,但是在输入序列后出现以下提示:
1 2Positions with correct letter: 1,0,0,0,-420947304,You have a total of5 correct letters
尽管我有中等的编程经验,但我还是刚开始学习c ++,所以我对语法等不是很精通。
答案 0 :(得分:1)
最有可能的问题是发生时发生的脱位越界
cin >> t[5];
这将从cin
中读取一个字符并将其写入五元素数组t
的第六个元素。这将导致undefined behavior。
现实中可能发生的事情是,内存中的下一个变量(很可能是u
(在t
旁边定义)将被您读取的值覆盖。
如果要读取字符串,则需要将指针传递到数组的第一个元素&t[0]
。您可以通过了解数组自然地 decay 指向指向其第一个元素的指针来简化此过程,这意味着t
将等于&t[0]
。所以你只需写
cin >> t;
请注意,没有边界检查C样式的字符串。如果用户输入的字符串长于四个字符,则仍然会遇到与多余字符相同的问题,并且空终止符将被写出数组的边界。解决方案是std::string
类:
string t; // A dynamic string which will be extended as needed
...
cin >> t;
答案 1 :(得分:0)
使用std::string
收集用户的猜测,因为使用固定大小的char数组可能导致未定义的行为。
一种解决方案可能是除非获得正确大小的猜测字符串(我的假设是您正在寻找一个固定大小的猜测),否则不要继续进行。
while(u<10) {
string guess;
cout << "Enter your guess ";
cin >> guess; // take guess attempt as an array, each letter at a different index
if (guess.size() != 5) {
continue;
}
/* Process the guess */
u++;
}