Fixing a weird write to file bug in c++ - c++

i got this really wierd problem, i'm writing my results to an output file, i use functions A B and C i activate them in that order, the results in the file is printed in a different order, first from A than from C and after that from B. i just can't understand why the results printed in a different order than the activation order. thanx.
the code :
void Manager::AddCommand(Command* com, ofstream &ResultFile)
{
if (com != NULL)
{
if (com->ValidCommand(ResultFile) == true)
commands.push_back(com);
else
delete com;
}
}
bool Command::ValidCommand(ofstream &Result) const
{
if(func<PrintCityCouncilList || func >HireEmployee){
Result << "Command:Failed activating function - invalid function number\n";
return false;}
if ((func == Command::PrintDepartmentEmployees) || (func == Command::PrintDepartmentExpenses) || (func == Command::PrintDepartmentStatistics)){
if(dept<Employee::Engineering ||dept>Employee::Sanitation )
{
Result << "Command:Failed activating function - invalid department number\n";
return false;
}
}
return true;
}
void Manager::ActivateCommand(Command* com, ofstream &Result)
{
if(com != NULL)
{
switch(com->GetFunction())
{
case (Command::PrintCityCouncilList): pcc->PrintCityCouncilDetails(Result);
break;
case (Command::PrintDepartmentEmployees):ActivatePrintDeprtEmployees(com->GetDepartment(), Result);
break;
case (Command::PrintEmployeeSalary):ActivateEmployeeSalary(com->GetId(), Result);
break;
case (Command::PrintDepartmentExpenses):ActivateDeprtExpenses(com->GetDepartment(), Result);
break;
case (Command::PrintCityCouncilExpenses): pcc->AllExpenses (Result);
break;
case (Command::PrintDepartmentStatistics):ActivateDeprtStatistics(com->GetDepartment(), Result);
break;
case (Command::FireEmployee): pcc->RemoveEmployeeFromCC(NULL,com->GetId(),Result);
break;
case (Command::HireEmployee): pcc->AddEmployeeToCC(com->GetId(),com->GetPrivateName(),com->GetSurName(),com->GetDate(),com->GetAddress(),com->GetDepartment(), com->GetStatus(),com->GetSalary(),com->GetPositionPercent(),com->GetPhoneNum(), Result);
break;
default:Result<<"Manager:Failed Activating command - invalid function"<<endl;
break;
}
}
}
void Manager::ActivateCommandsList(ofstream &Result)
{
Command* tmp = NULL;
if (commands.empty() == false)
{
list<Command*>::iterator iter = commands.begin();
while (iter != commands.end())
{
tmp = (Command*)(*iter);
ActivateCommand(tmp,Result);
iter++;
}
}
}

Ok here's the deal, your code maybe having some difficulties if you are running it in visual stdio. You see, it has some bugs when it tries to optimize your code. Turn optimization off. Also flush your stream, that's done when putting endl in cout and \n in printf. There is another possibility and it is Stack-Corruption or Heap-Corruption. Check to see if your dynamic objects are referenced within their boundaries.
As long as you don't send the code, like my friend just said we should consult the crystall ball.

My guess is that if this is homework, you are not having a threading issue. Have you tried to flush the output stream from A, B, and C? That might solve your problem.

Related

How to make a try catch recursion in a switch statement iterative?

I am trying to make a function that looks like below. I want to make it iterative, but I am not sure since I need to keep all paths open.
someFunction( parameters)
{
//do stuff
switch( thing )
case: one
if (something true)
{
try { someFunction( different parameters ) } catch(...) { throw }
case: two
//if else with the else being a throw exception.
case: three
// same
case: four
...
default
return some value
I didnt understand very well ur question, but i will try to help!
How to use EXCEPTIONS:
...
try
{
if(b == 0)
throw("A number cannot be devided by zero!\n");
c = a/b
}
catch(string error)
{
cout << "ERROR: "<< error << endl;
}
return c
...
You could use it in a switch statement, after the catch i will return to the case.
switch(c)
{
case 0:
...
try { ... throw();}
catch() { ... error treatment}
...
break;
case 1:
...
}

Adding split-screen multiplayer to c++ game

I am coding for the NDS in c++ with libnds, but this question is not NDS-Specific. I currently have a text-based game in which the top screen just displays a logo, and you play on the bottom screen.
So I want to add a type of single-DS multiplayer in which one player plays on the top screen, and the other on the bottom. I dont have a problem with setting up the text engine with both screens, I just need to find a method of efficiently coding in multiplayer. Below I wrote a summary or simplified version of it.
Note: consoleClear() clears the screen and the only spot where the game stops is att the pause function.
//Headers
void display(int x,int y,const char* output))
{
printf("\x1b[%d;%dH%s", y, x,output);
}
void pause(KEYPAD_BITS key) //KEYPAD_BITS is an ENUM for a key on the NDS
{
scanKeys();
while (keysHeld() & key)
{
scanKeys();
swiWaitForVBlank();
}
while (!(keysHeld() & key))
{
scanKeys();
swiWaitForVBlank();
}
return;
}
void pause() //Only used to simplify coding
{
pause(KEY_A);
return;
}
int main(void)
{
//Initializations/Setup
while (1)
{
if (rand()%2==1) //Say Hello
{
if (rand()%3!=1) //To Friend (greater chance of friend than enemy)
{
display(6,7,"Hello Friend!");
display(6,8,"Good greetings to you.");
pause();
consoleClear(); //Clears text
display(6,7,"Would you like to come in?");
pause();
//Normally more complex complex code (such as interactions with inventories) would go here
}
else //To enemy
{
display(6,7,"Hello enemy!");
display(6,8,"I hate you!");
pause();
consoleClear();
display(6,7,"Leave my house right now!!!");
pause();
}
}
else //Say goodbye
{
if (rand()%4==1) //To Friend (lesser chance of friend than enemy)
{
display(6,7,"Goodbye Friend!");
display(6,8,"Good wishes to you.");
pause();
consoleClear();
display(6,7,"I'll see you tomorrow.");
pause();
consoleClear();
display(6,7,"Wait, I forgot to give you this present.");
pause();
}
else //To enemy
{
display(6,7,"Goodbye enemy!");
display(6,8,"I hate you!");
pause();
consoleClear();
display(6,7,"Never come back!!");
pause();
consoleClear();
display(6,7,"Good riddance!"); //I think I spelt that wrong...
pause();
}
}
}
}
I know gotos are confusing and can be considered a bad habit, but I cant think of a better way. My version of integrating multiplayer:
//Headers and same functions
int game(int location)
{
switch (location)
{
case 1: goto one; break;
case 2: goto two; break;
case 3: goto three; break;
case 4: goto four; break;
case 5: goto five; break;
case 6: goto six; break;
case 7: goto seven; break;
case 8: goto eight; break;
case 9: goto nine; break;
case 10: goto ten; break;
default: break;
}
if (rand()%2==1) //Say Hello
{
if (rand()%3!=1) //To Friend (greater chance of friend than enemy)
{
display(6,7,"Hello Friend!");
display(6,8,"Good greetings to you.");
return 1;
one:;
consoleClear(); //Clears text
display(6,7,"Would you like to come in?");
return 2;
two:;
//Normally more complex complex code (such as interactions with inventories) would go here
}
else //To enemy
{
display(6,7,"Hello enemy!");
display(6,8,"I hate you!");
return 3;
three:;
consoleClear();
display(6,7,"Leave my house right now!!!");
return 4;
four:;
}
}
else //Say goodbye
{
if (rand()%4==1) //To Friend (lesser chance of friend than enemy)
{
display(6,7,"Goodbye Friend!");
display(6,8,"Good wishes to you.");
return 5;
five:;
consoleClear();
display(6,7,"I'll see you tomorrow.");
return 6;
six:;
consoleClear();
display(6,7,"Wait, I forgot to give you this present.");
return 7;
seven:;
}
else //To enemy
{
display(6,7,"Goodbye enemy!");
display(6,8,"I hate you!");
return 8;
eight:;
consoleClear();
display(6,7,"Never come back!!");
return 9;
nine:;
consoleClear();
display(6,7,"Good riddance!"); //I think I spelt that wrong...
return 10;
ten:;
}
return -1;
}
}
int main(void)
{
//Initializations/Setup
int location1 = -1, location2 = -1;
location1 = game(location1);
location2 = game(location2);
while (1)
{
scanKeys(); //Whenever checking key state this must be called
if (keysDown() & KEY_A) //A key is used to continue for player1
location1 = game(location1);
if (keysDown() & KEY_DOWN) //Down key is used to continue for player2
location2 = game(location2);
}
}
Aside from this method being a bad practice, in the actual source code, I have hundreds of gotos I would need to add which would be too time consuming.
Any help is appreciated. If anyone has the slightest of a question, or answer, please ask/reply.
Edit: Though it is not preferred to do so, I am willing to rewrite the game from scratch if someone has a method to do so.
Using if-else conditional statements for each case is a simple solution that comes first to mind.
For example:
int game(int i){
if(i == 1){
//first case code here.
}
else if(i == 2){
//second case code here.
}
//....
return 0;
}
The code in each case can even be put in other functions that will be invoked depending on each condition.
This will probably be enough for your case.
A more flexible solution (but much more complex) is a dispatch table.
The idea is to have separate functions with each desired functionality, and put pointers of them in an array. Then, you can call them by indexing the table, using those function pointers. This can be extremely helpful if you have a sequence of executions (function invokes) to be done and you want to set it done easily, or you want to have different results depending on your input, without changing your program.
There is an example below.
This code can be used in C too, if you replace std::cout with printf and iostream with stdio library.
#include <iostream>
using namespace std;
// Arrays start from 0.
// This is used for code
// readability reasons.
#define CASE(X) X-1
typedef void (*chooseCase)();
// Functions to execute each case.
// Here, I am just printing
// different strings.
void case1(){
cout<< "case1" << endl;
}
void case2(){
cout<< "case2" << endl;
}
void case3(){
cout<< "case3" << endl;
}
void case4(){
cout<< "case4" << endl;
}
//Put all the cases in an array.
chooseCase cases[] = {
case1, case2, case3, case4
};
int main()
{
//You can call each scenario
//by hand easily this way:
cases[CASE(1)]();
cout << endl;
//Idea: You can even set in another
// array a sequence of function executions desired.
int casesSequence[] = {
CASE(1), CASE(2), CASE(3), CASE(4),CASE(3),CASE(2),CASE(1)
};
//Execute the functions in the sequence set.
for(int i = 0; i < (sizeof(casesSequence)/sizeof(int)); ++i){
cases[casesSequence[i]]();
}
return 0;
}
This will print at the output:
case1
case1
case2
case3
case4
case3
case2
case1

Throwing exception versus returning a result code

I'm creating a library. I want to make a fixed-length string class.
#include <string>
#include <iostream>
#define OK 0
#define TOO_LONG 1
#define UNALLOWED_CHARACTERS 2
struct MyString {
MyString(int l)
: m_length(l) { }
struct exception {
exception(int t, MyString *p)
: type(t), ptr(p) { }
int type;
MyString *ptr;
};
int set(const std::string& name);
void set2(const std::string& name) throw(exception);
std::string m_str;
int m_length;
};
int MyString::set(const std::string& s)
{
if(s.size() > 64) {
return TOO_LONG;
} else if(s.find('~') != std::string::npos) {
return UNALLOWED_CHARACTERS;
} else {
m_str = s;
return OK;
}
}
void MyString::set2(const std::string& s) throw(exception)
{
if(s.size() > m_length) {
throw exception(TOO_LONG, this);
} else if(s.find('~') != std::string::npos) {
throw exception(UNALLOWED_CHARACTERS, this);
} else {
m_str = s;
}
}
int main()
{
using namespace std;
//OPTION 1
{
MyString s1(10);
MyString s2(10);
int code;
code = s1.set("abcdefghijX");
switch(code) {
case TOO_LONG:
//handle <--
break;
case UNALLOWED_CHARACTERS:
//handle
break;
default:
//ok!
break;
}
code = s2.set("abcdefghi~");
switch(code) {
case TOO_LONG:
//handle
break;
case UNALLOWED_CHARACTERS:
//handle <--
break;
default:
//ok!
break;
}
}
//OPTION 2
{
MyString s1(10);
MyString s2(10);
try {
s1.set2("abcdefghijX");
s2.set2("abcdefghi~");
} catch(MyString::exception &e) {
cerr << "MyString::exception: ";
auto p = e.ptr;
if(p == &s1) cerr << "s1 ";
else if(p == &s2) cerr << "s2 ";
switch(e.type) {
case TOO_LONG: cerr << "too long"; break;
case UNALLOWED_CHARACTERS: cerr << "unallowed characters"; break;
}
cerr << endl;
}
}
}
I don't know which version of MyString::set() I should use. What is the convention in such cases? I used STL in this example for demonstration purposes.
It is a good idea to mimic the behavior of the standard library functions unless one has a specific reason not to. BTW, since tr1, STL has a fixed-length string class built in. Lets see what it does. The only example implementation I have handy is Visual C++ 2010.
std::tr1::array&LT;int,5> arry;
arry[10] = 42; // Oopsie. There is no element 10.
When compiled and run as the "Debug" version, I get an assert failure. When compiled for "Release" the offensive statement quietly does ... NOTHING. It is optimized right out of existence. Okay, maybe that is not always what one would want. Forget what I said about mimicking the STL, or at least Microsoft's implementation. Train of consciousness continues...
I think it is fair to say that if the program tries to set an out of range cell, that is a logic error in the program. In mission-critical software it might be a good idea to have code in place to deal with a situation like that and recover from it, while trying like heck to make sure it can never, never happen.
So the answer is, throw an exception of type std::out_of_range.
So there.
In general in C++ it's recommended to use exceptions to indicate errors unrecoverable in the current context. But it depends on purpose. You may want to compile your library in an embedded environment using no exceptions (for sake of efficiency), then you have to go with return codes.
Its easy to wrap an API using return codes to one that uses exceptions, but no way vice versa.
EDIT:
Some more reasoning why it may make sense not to use exception handling:
Exception handling usually introduces additional information about try/catch blocks necessary to be placed in the call stack + some performance penalty to build and check these informations.
See also: performance of C++0x exceptions

Why can't I have a variable in switch-case statement? [duplicate]

This question already has answers here:
Case expression not constant
(5 answers)
Closed 5 years ago.
Here is my code:
bool Character::keyPress(char c)
{
switch(c)
{
case up_key:
move(0, -1);
break;
case down_key:
move(0, 1);
break;
case left_key:
move(-1, 0);
break;
case right_key:
move(1,0);
break;
default:
return false;
}
return true;
}
And the compiler complains:
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
In my header file I have:
protected:
char up_key;
char down_key;
char right_key;
char left_key;
I am using Visual C++ 2008.
As the error message states, the case expressions must be constant. The compiler builds this as a very fast look-up table at compile time and it can't do that if there is a possibility that the values could change as the program runs.
If you do need them to be variable, not constant, your best bet is to use if/else statements instead.
Replace this long clumsy code,
switch(c)
{
case up_key:
move(0, -1);
break;
case down_key:
move(0, 1);
break;
case left_key:
move(-1, 0);
break;
case right_key:
move(1,0);
break;
default:
return false;
}
with something like this:
move( (c==right_key) - (c==left_key) , (c==down_key) - (c==up_key) );
You can litterly replace that 17 lines long of code with that much more neat single line of code.
You can't because the language doesn't work that way. For example, what would happen if up_key, down_key, right_key, and left_key were all equal?
Because the switch statement can take only constants, you know when reading the code that the things you're comparing against are all constants. On the other hand, you would use if statements (or some other structure) to compare against variables:
if (c == up_key) {
move(0, -1);
} else if (c == down_key) {
move(0, 1);
} else ...
This provides a distinct difference in structure which can greatly aid those who come after you in reading your code. Imagine if you had to look up every case label to see whether it was a variable or not?
I believe it's because the compiler generates a jump table, with the values hardcoded in, although I may be wrong. The way the tables are generated just doesn't allow for it.
Since other answers have covered why you are getting an error, here is a way to move in one of the four directions in response to a key press: use lookup tables instead of the conditionals/switches.
Setup portion:
std::map<char,pair<int,int> > moves;
moves[up_key] = make_pair(0, -1);
moves[down_key] = make_pair(0, 1);
moves[left_key] = make_pair(-1, 0);
moves[right_key] = make_pair(1, 0);
The function:
bool Character::keyPress(char c) {
if (moves.count(c)) {
pair<int,int> dir = moves[c];
move(dir.first, dir.second);
return true;
} else {
return false;
}
}
//here is the full functional code snippet which can be compiled and run with most of C++
//compiler/link ...console app was demoed but you can apply the code/logic to win32 app...
//if you have any problem, send me email to Samuel_Ni#yahoo.com
#include <iostream.h>
#include <map>
#include <conio.h>
class CkbdHanler{
private:
map<char,pair<int,int> > moves;
protected:
char up_key;
char down_key;
char right_key;
char left_key;
public:
CkbdHanler(char a,char b,char c,char d):up_key(a),
down_key(b),
right_key(c),
left_key(d)
{
moves[up_key] = make_pair(0, -1);
moves[down_key] = make_pair(0, 1);
moves[left_key] = make_pair(-1, 0);
moves[right_key] = make_pair(1, 0);
}
bool keyPress(char c){
if (moves.count(c)) {
pair<int,int> dir = moves[c];
move(dir.first, dir.second);
return true;
} else return false;
}
void move(int i,int j){
cout<<"(i,j)=("<<i<<","<<j<<")"<<endl;
}
};
int main(int argc, char* argv[])
{
CkbdHanler CmyKbdH('u','d','l','r');
cout << "Hello C++... here is a demo of Map to replace switch-case" << endl;
CmyKbdH.keyPress('d');
cout << endl << "Press any key to continue...";
getch();
return 0;
}

C++ console game input && refresh function

I am writing a small console adventure game and I faced a few problems.
1. The input is kinda laggy, I'm using while loop ( while(getch() == 'w') ). After a key is pressed the first time, nothing happens (you have to press it 2 times) and if you switch directions (press key A/D/S) it also doesn't react the 1st time. If you hold a key, it works fine. How can this be fixed?
2. Here's the function I use to refresh game (render the game scene when a key is pressed):
void refresh(char map[Y][X])
{
system("cls");
for (int i = 0; i<UP; i++)
{
cout<<endl;
}
for (int i = 0; i<Y; i++)
{
for (int k = 0; k<LEFT; k++)
{
cout<<" ";
}
for (int j = 0; j<X; j++)
{
cout<<map[i][j];
}
cout<<endl;
}
}
When I use this function once, it's ok, but when they key is pressed or held multiple times - the game field starts to flash. I figured that I need to redraw only a part of the field (where changes are made/movements are done), not the whole field. Can you offer any ideas how to do that?
The sample code for input:
while(getch() == 'w')
{
if (map[y-1][x]!= WALL)
{
map[y-1][x] = CHARACTER;
map [y][x] = ' ';
y--;
refresh(map);
Sleep(SPEED); // this is unnecessary, SPEED is 0, I just kept it for tests
}
}
Basically, the main function looks like this:
int main()
{
(...) Variables (...)
generateMap(FROM FILE);
refresh(); // First initialization of the field
while (getch() != 'q') // While not quitting
{
while(getch() == 'w')
{
if (THE FIELD ABOVE IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 's')
{
if (THE FIELD BELOW IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'a')
{
if (THE FIELD ON THE LEFT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'd')
{
if (THE FIELD ON THE RIGHT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
return 0;
}
Don't use system("cls"), it is really slow, instead set the cursor on the beginning of the screen with the following code:
COORD cur = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur);
You should call getch() only one time in the loop, like this:
char key;
do
{
key = getch();
if(key == 'w')
{
//do something
}
//the other if statements
}while(key != 'q');
The code should have only one getch() in the whole code (if possible) and inside a switch you do the action for each input. So, it is switch inside the loop, and not loops inside the switch. Something like this:
while ((ch = getch()) != 'q')
{
switch (ch)
{
case 'a':
GoLeft();
break;
...
}
}
There is a library called ncurses that you can use to move the cursor around the screen, and write anything anywhere.
It looks like your problem is calling getch() multiple times. Have only one loop, and call getch() once per loop, and store the result. Test that result for each value (q, w, s, ...) for each iteration of the loop.
I would recommend you to use function input() as it stands:
void input()
{ if (GetKeyState('W') & 0x8000) // That means when button "W" is pressed
... your code ...
// (changes global variables, or you can pass variables by reference)
}
without any getch() command that stops your game every single time.
You can use it with the draw() and calculate()/refresh() functions in the main(), like:
int main()
{
... other part of code ...
while (!gameover)
{
input();
calculate();
draw();
}
}
so that you will always have some sort of input value before the calculations, and then you would draw (+ it's much easier to debug ;) )