我直接上源代码吧,在stringguess函数里面,开辟空间之后第一个是有空格存在,第二个是在开辟四个空间之后,后面就有乱码。
#include<iostream>
#include<stdlib.h>
#include<ctime>
#include<windows.h>
#include<string>
#include<fstream>
using namespace std;
class guessGame
{
int Diffcluty,i;
char* systemChar=0, * userChar=0;
string userName;
public:
guessGame(int n) :Diffcluty(n),i(1) {};
char Random(int Difficulty);/*生成随机数*/
void func();
void GameInterface();/*游戏界面*/
void StringGuess();
void RankingList();/*游戏排行榜*/
~guessGame()
{
if (systemChar != NULL)
{
delete[]systemChar;
systemChar = NULL;
}
if (userChar != NULL)
{
delete[]userChar;
userChar = NULL;
}
}
};
char guessGame::Random(int Difficulty)
{
char randomInt, randomChar, randomCharSup, randomAll;
randomInt = rand() % 9 + 48;
randomChar = rand() % 25 + 65;
randomCharSup = rand() % 25 + 97;
randomAll = rand() % 93 + 33;
switch (Difficulty)
{
case 1:/*纯数字*/
{
return randomInt;
break;
}
case 2:/*数字字母组合*/
{
int i = rand() % 2 + 1;
if (i == 1)
{
return randomInt;
}
else if (i == 2)
{
return randomChar;
}
else
{
return randomCharSup;
}
break;
}
case 3:/*全键盘字符*/
{
return randomAll;
break;
}
}
}
void guessGame::func()
{
GameInterface();
StringGuess();
RankingList();
}
void guessGame::GameInterface()
{
getchar();
cout << "游戏难度选择已完成!\t按下回车键开始游戏";
getchar();
cout << "游戏开始倒计时3秒!\n";
for (int i = 0;i < 3;i++)
{
/*Sleep(1000);*/
cout << 3 - i << '\n';
}
cout << "游戏开始!";
system("cls");
}
void guessGame::StringGuess()
{
while (1)
{
cout << "第" << i << "轮的字符是:\n";
systemChar = new char[i];
userChar = new char[i];
for (int n = 0;n < i;n++)
{
systemChar[n]=Random(Diffcluty);
cout << systemChar[n];
}
Sleep(1000);
system("cls");
cout << "请输入你记住的字符";
for (int n = 0;n < i;n++)
{
cin >> userChar[n];
}
if (!strcmp(systemChar, userChar))
{
getchar();
cout << "恭喜您猜对了^_^!\n输入回车键进行下一轮";
delete[]systemChar;
systemChar = 0;
delete[] userChar;
userChar = 0;
i++;
getchar();
system("cls");
}
else
{
cout << "猜错了×_×!正确答案是:" << systemChar;
cout << "\n您一共进行了" << i<< "轮\n请输入你的名字:";
cin >> userName;
break;
}
}
}
void GameOperation() /*游戏说明书*/
{
system("cls");
cout << "--------------------游戏说明--------------------\n";
cout << "玩法:程序会随机显示字符,在规定时间后消失,凭记忆输入这些字符\n";
cout<<"在每次正确输入后,字符数会增加一个,直到用户输入错误(只要有一个字符不对就算错),这一轮游戏结束\n";
cout << "本程序具有记录用户成绩排行榜功能。\n";
cout << "\t简单模式:由随机的纯数字组成\n";
cout << "\t中等模式:由随机的数字与大小写字母组合而成\n";
cout << "\t困难模式:由随机的全键盘字符组合而成\n";
cout << "\t重新查看游戏说明请按0\t简单难度输入1\t中等难度输入2\t困难难度输入3\n请选择:";
}
int main()
{
//问题一:内存分配时无效
//问题二:文件读取被覆盖
srand(time(NULL)); //随机数放到主函数中防止产生重复随机数
int Diffculty;
cout << "\t查看游戏说明请按0\t简单难度输入1\t中等难度输入2\t困难难度输入3\n请选择:";
cin >> Diffculty;
while (1)
{
if (Diffculty == 0)
GameOperation();
else if (Diffculty < 0 || Diffculty>3)
{
cout << "输入错误,请重新输入!";
}
else break;
cin >> Diffculty;;
}
guessGame sSs(Diffculty);//适当调整时间 当每超过2个字符时增加1秒
sSs.func();
}