Joined: 01 May 2007 Posts: 266 Location: Ontario, Canada
Posted: Fri Jan 27, 2012 11:06 am Post subject: C++ Data validation
Just started learning C++ and got stuck while writting my code, the code works fine but if a user enters something other than a number it craps out.. if anyone could give me a hand I would appeciate it
int main()
{
int score[5][3];
int currentScoreAvg=0;
int totalScore=0;
int playerScore=0;
for (int player = 0; player<5; player++)
{
cout << "Player "<<player+1<<endl;
for(int game = 0; game<3; game++)
{
cout<< "Please Enter Score \n";
cin>> playerScore;
if(playerScore>300 || playerScore<0)
{
cout<<"Please enter a valid score between 1-300 inclusive \n";
game--;
cout<< "Average score for this player is "<< currentScoreAvg/3<<endl;
totalScore+=(currentScoreAvg/3);
currentScoreAvg=0;
}
cout <<"Average score for whole team is " <<totalScore/5<<endl;
system ("pause");
}
int main()
{
int score[5][3]; //array to hold the score for each user and the current player
int currentScoreAvg=0; //variable to hold the users current average score
int totalScore=0; //variable to hold the total score (all users)
char playerScore; //variable to hold the input from the user (players Score)
for (int player = 0; player<5; player++)
{
cout << "Player "<<player+1<<endl;
for(int game = 0; game<3; game++)
{
cout<< "Please Enter Score \n";
cin>> playerScore;
if(playerScore>300 || playerScore<0 || isalpha(playerScore))
{
cout<<"Please enter a valid score between 1-300 inclusive \n";
game --;
}
else
{
score[player][game] = playerScore;
currentScoreAvg += score[player][game];
}
}
cout<< "Average score for this player is "<< currentScoreAvg/3<<endl;
totalScore+=(currentScoreAvg/3);
currentScoreAvg=0;
}
cout <<"Average score for whole team is " <<totalScore/5<<endl;
system ("pause");
}
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum