So basically, i'm writing a small game in c++. What you see is the skill point distribution function.
This is just a small solution I created to try and isolate the error, and i've been able to figure out so far that there is a problem with calling the answer for switch along with calling another user input function within the switch.
Basically the loop will have run three times by the end of the program when it is supposed to have only run twice.
This is what is happening:
1. loop runs
2. switch (user is asked for a char)
3. case chosen 's'
4. user is asked for a number
5. add points and restart loop
6. skip switch answer and go straight to default:
7. restart loop
8. switch waits for input. (three loops, where only two should have run)
Obviously I have excluded other cases, and an exit/return.
Hope you guys can help!
IDE: Visual C++ 2008 Express
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <string>
#include <windows.h>
#include <istream>
#include <sstream>
using namespace std;
char GetSingleChar();
int GetNum();
int main ()
{
bool validInput(0), stop(0);
int points[3] = {0, 0, 0}, sPts, p;
sPts = 5; // skill points for player to use
for(int x=0;x>3;x++){points[x]=0;} //need to use this to reset variables when it was inside the rest of the game. Otherwise in this case it's pretty pointless.
do
{
cout << "\nYou have " << sPts << " points left. Which attribute would you like to add points to?\n\n";
cout <<"s - Strength (" << points[0] << ")";
cout << "\nChoice: ";
switch(GetSingleChar()) // ask user for answer
{
case 's':
if(sPts>0) // make sure user still has skill points left
{
do // loop to make sure user enters a correct number
{
cout << "blah blah strength points left is " << sPts << "\n\nStrength: ";
p = GetNum();
// excluding this and makeing something like p = 1; gets rid of my problem entirely. I have even tried not using this function and doing a simple cin >> p; but that also screws it up.
points[0] += p;
validInput = 1;
if (points[0] <= sPts && points[0] >= 0)
{
sPts -= points[0];
validInput = 1;
}
else {cout << "Can't use that many points!";}
}while(!validInput);
validInput = 0;
}
else {cout << "Sorry, you have no more points left to spend.";}
system("cls");
stop=0;
break;
default:
cout << "activated default!";
Sleep(5000);
stop=0;
}
}while(!stop);
return 0;
}
char GetSingleChar()
{
string user_input="\0";
char newChar='\0';
getline(cin, user_input);
newChar += user_input[0];
return newChar;
}
int GetNum()
{
int result(0);
string text;
istringstream iss;
do
{
cin >> text;
iss.clear();
iss.str(text);
if(!(iss >> result))
{
cerr << text <<" is not a number\n\nChoice: ";
}
} while(!iss);
return result;
}
|