我正在創建一個猜謎遊戲。每次用戶再次猜測時,我都需要顯示用戶以前的猜測。我正在使用數組和指針。下面的代碼僅顯示用戶輸入的最新內容。我需要它顯示以前輸入的列表。包含指針的代碼部分似乎是我的問題所在的位置,但我不確切知道在哪裏?如何在用戶使用數組猜測新數字之前顯示以前的猜測列表?
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
int reviewGuess(int Answer, int userGuess);
int _tmain(int argc, _TCHAR* argv[])
{
int guessNum = 3; // Declares how many guesses the user can take.
int userGuess = 0;
int Answer;
char Choice;
int *pointer = NULL;
srand(time(NULL));
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
do{
int x;
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << guessNum << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
for (int i = 0; i < guessNum; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << i + 1 << " : "; //Takes the user input
cin >> userGuess;
int guessNum = 1;
pointer = new int[guessNum];
for (int i = 0; i < guessNum; i++) //Store the user guesses
{
*(pointer + i) = userGuess;
}
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < guessNum; i++) // Display the user guesses.
{
cout << " Guess# " << i + 1 << " is " << *(pointer + i) << endl;
}
reviewGuess(Answer, userGuess); //Calls the function
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
int reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess > Answer)
cout << " -----> 1 \n";
else
cout << " -----> -1 \n";
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return 0;
}
}
歡迎計算器!這是很多代碼......你可以縮小到[MCVE](http://www.stackoverflow.com/help/mcve)嗎?有時候,這樣做的行爲會使你的答案顯而易見,最起碼,它使我們更容易找到答案。 :) – CodeMouse92
^一個關鍵的技能,你將需要學習反正(「調試」!) –
'pointer = new int [guessNum];'每次分配一個元素的數組。後面的兩個'for'循環用最近的猜測填充該數組,然後顯示它。在這裏有一個元素的數組是沒有意義的。 – Logicrat