object is not being saved even after fstream.clear() in c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am using C++ to write a music memorize game for my school project, here the Player objects are not being saved in the PLAYER_DATA.DAT file even i tried clear() function
here is the peace of code (as the whole code is 600+ lines)
Player p_dat,plyr;
plyr.getData();
fstream P_file("PLAYER_DATA.DAT",ios::out|ios::in|ios::binary);
while(P_file.read((char*)&p_dat, sizeof(p_dat)))
{
if(nameEqual(plyr,p_dat))
{
P_file.clear();
gotoxy(1,10);
delline();
textcolor(RED);
cout<<"\t\t EXIXTING PLAYER PROFILE FOUND!\n";
int ch = playPanel("It's me", "Change Name");
if(ch == 0)
{
P_file.seekp(P_file.tellg() - sizeof(Player));
GameStarted = 1;
if(c == 1)
Campaign(p_dat,P_file);
else
Endless(p_dat,P_file);
return;
}
else
{
startGame(c);
return;
}
}
}
P_file.clear();
P_file.seekp(0,ios::end);
P_file.write((char*)&plyr,sizeof(plyr));
Just to make it short, The last line of the code is not doing anything the file already exists and of size 0kb
however,
fstream P_file("PLAYER_DATA.DAT",ios::out|ios::in|ios::binary)
P_file.write((char*)&plyr,sizeof(plyr));
is saving the file. Please help me.
EDIT 1.1
finally found this line is problematic
P_file.seekp(0,ios::end);
Its working for code, i.e correctly saving objects
P_file.clear();
P_file.write((char*)&plyr,sizeof(plyr));
P_file.seekp(0,ios::end);
while removing
P_file.seekp(0,ios::end);
making the code look like,
P_file.clear();
P_file.write((char*)&plyr,sizeof(plyr));
after the while loop, is not saving the file
again does not save the object
this line is making problem, are there any alternatives or solutions?

Compile with all warnings and debug info (g++ -Wall -Wextra -g with GCC) then use the debugger (e.g. gdb).
Read carefully documentation of C++ IO functions.
Check that your file has been opened correctly; after:
fstream P_file("PLAYER_DATA.DAT",ios::out|ios::in|ios::binary);
add
if (!P_file) { std::cerr << "failed to open PLAYER_DATA.DAT" << std::endl; };
On some systems (e.g. Linux), you might also display strerror(errno).
After some intermediate call to write, consider using flush.
Be sure that your program is started in the correct working directory.
On Linux, you might also use strace(1) to understand the system calls done by your program.
At last, did you consider using some simple database, e.g. with sqlite, or some indexed file, e.g. with gdbm ?

Related

ERROR: Thread 1: EXC_BAD_ACCESS (code=1, address=0x68) FIX: PLACE THE IN AND OUT FILES IN THE WORKING DIRECTORY OF THE PROJECT [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I get this error:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x68)
on the following line:
while(fscanf(f,"%d", &a[x])==1)
1st time trying to do my class homework in Xcode, used code blocks before and managed to run this same code on it, any help is much appreciated!
#include <cstdio>
int a[1001];
int main()
{
int aux1,aux2,aux3,x=0;
FILE *f,*g;
f=fopen("1.in","r");
g=fopen("2.out","w");
while(fscanf(f,"%d", &a[x])==1) //HERE
{
aux1=a[x];
aux2=0;
aux3=0;
while(a[x]!=0)
{
aux2=aux2*10+a[x]%10;
a[x]=a[x]/10;
aux3=aux3*10+9;
}
if(aux3-aux2==aux1)
fprintf(g,"1 ");
else fprintf(g,"0 ");
x++;
}
fclose(f);
fclose(g);
return 0;
}
To find out if you put the in and out files in the working directory you must try to print the read numbers in a terminal, if it doesn't print anything then I your .in and .out files are outside the working directory.
Debug:
After this line :
fscanf(f,"%d", &n);
do:
printf("%d", n);
if it prints the number well, guess your files are in the working directory, just make sure .out and .in are in the same directory and that's it.
Make sure that you actually opened 1.in file by checking what open() had returned. Make sure that you do not go outside of array bounds, if x reach 1001, something bad may happen, it's an Undefined Behaviour.
The problem was that I placed 1.in and 1.out outside the working directory, to fix this had to go to Product>Scheme>Edit Scheme>Run>Options and set a custom "Working Directory" where I placed the 1.in and 1.out files. Thanks for the help guys.

Is it possible to create "quick time events" in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have some knowledge about C++, but I stumbled upon an problem. I want the user to enter some text, but when it takes longer than X seconds, the program will go on. I guess, it is not possible, but maybe you know something about it.
It will be in the command line, without GUI.
I am not certain how the programm will look like, but it will be something like a CMD-RPG. I wanted to use Quick Time Events to make it a little bit more exciting.
I cant comment so I will just leave this here
Input with a timeout in C++
Since I cannot comment, I will simply leave this as an answer.
One possible way to solve this problem is to have 2 threads:
Input capture thread: since receiving input is a thread-blocking action, you should have a thread that simply polls for user input, placing that input into a thread-safe buffer
Quick-time function on main thread: a function that will be responsible for executing the quick-time event. Something like the following could be done (pseudo code):
clear input buffer //the buffer provided by the input capture thread
bool success = false;
while(current time < ending time)
{
if(input buffer isn't empty)
{
get contents of input buffer and send contents to cout
if (user has finished input correctly)
{
success = true;
break;
}
clear buffer
}
}
return success;
For this to work, you would need to turn off echo on the command prompt (see this page for more info)
Although Diogo's reference is excellent (and informative), I believe this answer is more applicable than since the OP has indicated that this program will be ran on Windows.

C++ Text Files usage [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am currently learning how to use text files, but when i put a condition like the one in the code below, even if the condition is true it won't try the while part. Can anyone help out?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string s, d;
ofstream k("t1.txt");
int a;
cin >> a;
if (a > 3)
{
while (k.is_open())
{
getline(cin, s);
k << s;
k.close();
}
}
ifstream r("t1.txt");
while (r.is_open())
{
getline(r, d);
cout << d;
r.close();
}
}
I ran the code in gdb, it runs perfectly. It opens the file, gets the < cr > character from stdin, writes that to the first line which wipes out the first line, then tries to read the first line which is empty so there is no output. Good job 8).
You're just having trouble understanding your own expectations, your code works fine, so just think a little bit more about what you think it's supposed to do.
You'll also need to examine the contents of your text file before and after running the code, and try entering some text in the text file before you start the program, to see what happens to the text.
The getline where you try to read from the console is the issue, that returns without asking for input so it ends up giving you a blank line to write to the file.
From this link:
http://www.cplusplus.com/forum/beginner/39549/
There's a similar question there, and the first of the comments mentions this about the behavior of getline:
std::cin leaves the newline character in the buffer after pressing enter, and getline just grabs it and keeps going, that's why getline doesn't block to wait for input. .......
That's why it's not "doing anything" - it's not asking you for input, so the program has nothing to output and it looks like it's not working.
(this, by the way, is why programmers are snarky - we have to deal with stupid little behavioral issues of machines and we forget that PEOPLE are not normally like this and that PEOPLE hate being held to these kinds of standards)
I put a second getline in your code right after hte first one and now it asks for and outputs a string that I type in and sticks it in the file.
To run the program in gdb, do the following:
g++ -g < your cpp file > -o < whatever you want the binary to be called >
like this:
g++ -g myfile.cpp -o myrunnableprogram
this creates a binary with symbols that you can open in gdb
then
gdb myrunnableprogram
then in gdb
start
next
next
next
....
these commands will start the program and pause it at the first breakable spot, then each time you type next you will step to the next command and you can poke around at variables to see what's going on.
read up on gdb, it's really useful.

How do I tell a program where to start reading a .txt file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want my program to be able to remember where it left off in a .txt file in order to proceed to the next input upon reiteration through a loop.
For instance, a text file containing:
Apples
Bananas
Oranges
would be accessed through a function GetItem() that appends the next file input into a vector of items. How do I make the function add Apples the first time, Bananas the second time, and Oranges the third iteration? As of now, each call to GetItem() keeps adding the first element to the vector, giving a vector containing:
Apples
Apples
Apples
Because the file keeps opening from the beginning. Any help would be appreciated.
This is a simplified version of lengthy amounts of code that I could include, but would distract from the main purpose of the question. If the code is needed, I would be happy to include it.
vector<Item*> AddItemToInventory(vector<Item*> inventory) {
if (inptLctn == 'f') {
inptFile.open("TestFood.txt");
if (!inptFile.is_open()) {
cout << "Could not open file." << endl;
exit(1);
}
inptFile >> usrInptName;
inptFile >> usrInptQnty;
inptFile >> usrInptExpr;
inptFile >> usrInptPrice;
}
prdc = new Produce;
prdc->SetName(usrInptName);
prdc->SetQuantity(usrInptQnty);
prdc->SetExpiration(usrInptExpr);
prdc->SetPrice(usrInptPrice);
inventory.push_back(prdc);
return inventory;
}
Open the file before you use it and close it after you are done using it. The problem is that you are continually closing the input file so when you re-open it, it starts at the beginning again.
You should only open and close your input file once.

What is the fastest text rendering method in a command prompt when using C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
ATM I'm working on a game so I'm looking for a method to render an entire area of chars in' a blink of an eye. Now I'm having trouble with slow rendering speeds (or rather printing speeds to be specific here and I know cout a slow method but that was like the first option I'm using now)
So is there some way of displaying text fast enough so I won't have trouble with characters flickering or simply characters being drawn one after another because I'm using loops to draw them.
Any advice is apreciated
edit: even when everyone is downvoting this like hell I think this is a decent question that is useful for beginning programmers. Instead of endless hours of scouting the internet I now have an actual idea of how I should tackle this issue
The C++ standard input/output library is very limited when it comes to the operations that can be done in regards to the traditional terminal support.
Your only way out of this is to use a specialized library. As I mentioned in my comment, ncurses or pdcurses should suffice, depending on the platform you're on.
Just a quick comparison shows that cout in Visual Studio is a lot slower than printf (noticeable difference) - I will return with an edit of exactly how big a difference.
Obviously, a library for UI operations is likely to be much better, as it has the ability to move cursor around, and only redraw bits of the screen that actually changed, etc.
Edit: I used the following code to measure the speed of the two output methods:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <ctime>
int main(int argc, char **)
{
clock_t t = clock();
for(int i = 0; i < 40; i++)
{
if (argc == 1)
{
std::cout << "0123456789012345678901234567890123456789012345678901234567890123456789\n";
}
else
{
printf("0123456789012345678901234567890123456789012345678901234567890123456789\n");
}
}
std::cout.flush();
t = clock()-t;
std::cout << "Time = " << std::setprecision(3) << t / (double)CLOCKS_PER_SEC;
return 0;
}
On my machine, it takes approximately 0.1s (0.098-0.113s) with printf ('mytest x') and around 0.8s (0.776-0.860) with the cout ('mytest').