下面我粘贴了一些我写的代码。我遇到的问题是,当 turnmessage 将一个数字传递给 found() (通过引用)时,它会以某种方式急剧增加。例如,如果传入 3,我将收到 300 万。
(以下在文件 projectmain.cpp 中)
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "project1.h"
using namespace std;
project1 game;
string str(int number){
stringstream ss;
ss << number;
string result = ss.str();
return result;
}
void project1::setNames(){
string name;
cout<< "Player one, enter your name: ";
cin >> name;
playerOneName = name;
cout<< "Player two, enter your name: ";
cin >> name;
}
void project1::resetBoard(){
for(int i = 0; i < 3; i++){
RowOne[i] = str(i + 1);
RowTwo[i] = str(i + 4);
RowThree[i] = str(i + 7);
}
int used[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
turn = 1;
}
void project1::printBoard(){
for(int i = 0; i < 3; i++){
cout << " | " << RowOne[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowTwo[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowThree[i] << " | ";
}
cout << endl;
}
string project1::PlayerOneName(){
return playerOneName;
}
string project1::PlayerTwoName(){
return playerTwoName;
}
bool project1::found(int& number){
cout << " your number after pass: " << number;
int i = 0;
bool found = false;
while(i < 9 && found == false){
cout << used[i];
if(used[i] == number)
found = true;
i++;
}
return found;
}
void project1::turnmessage(){
int number = -1;
bool found;
do{
if(turn == 1)
cout << PlayerOneName();
else
cout <<PlayerTwoName();
cout << " it's your turn!" << endl << "Enter the number you wish to use: ";
cin >> number;
number--;
bool found = game.found(number);
if (found == true)
cout << "Sorry, that has already been used. Please try again.";
}while(found == true);
}
int main(){
game.setNames();
game.resetBoard();
game.printBoard();
game.turnmessage();
return 0;
}
(以下在文件 project1.h 中)
#include<string>
#include<iostream>
using namespace std;
class project1{
public:
void setNames();
void resetBoard();
void printBoard();
void turnmessage();
string PlayerOneName();
string PlayerTwoName();
bool found(int&);
private:
int playerOneScore;
int playerTwoScore;
string playerOneName;
string playerTwoName;
string RowOne[3];
string RowTwo[3];
string RowThree[3];
int used[9];
int turn;
};