Turbo C++ File Handling: Stuck in input loop - turbo-c++

I am making a program in turbo C++ to create student records and modify/delete them in a binary file on user's command.
The main class that is needed to know is the student class:
class student
{
private:
int roll_no;
char name[50];
academic ac;
co_curricular cc;
void calculate();
public:
int get_data(int);
void show_data();
void show_tabular();
int ret_roll_no();
};
There is some problem with the get_data() function, specially in the part where the roll number is assigned. The logic to assign the roll number is:
student temp;
fstream fp;
roll_no = random(9000) + 1000;
//Checking if roll number is unique
fp.open("STUDENT.DAT", ios::in);
while(!fp.eof())
{
fp.read((char*)&temp, sizeof(temp));
if(roll_no == temp.ret_roll_no())
roll_no = random(9000) + 1000; //Set roll number to another random value
}
fp.close();
Binary file STUDENT.DAT already exists, but the code doesn't go after the loop. It is somehow stuck.
Please help

Related

After I declare an object from a class, and try to set a variable to that object inly, why does it say that it does not declare a type?

I am writing code for a school project that will be used for a Chromebook charging station with security. The problem I am having now is when I am detecting if a Chromebook is actually in the slot after the user has been assigned one, I am using a rocker switch to simulate this but when I am declaring the pin to the rocker, the arduino verfier comes up with that
"'slot1' does not name a type".
Code is below:
//class
class Chromebook_slot {
public:
String Name = "";
String RFID_tag = "";
int rocker = 0;
boolean chromebook_in = false;
//class function to check if chromebook is in.
//if not, redirect already to reassigning so chromebook slot is entered as open and free.
void set_if_in()
{
int momen_1_state = digitalRead(momen_1);
int momen_2_state = digitalRead(momen_2);
// the button has been pushed down and the previous process has been completed
// eg. servos would have been reset if there was a previous user
if (momen_1_state == HIGH || momen_2_state == HIGH)
{
chromebook_in = digitalRead(this->rocker);
if (chromebook_in == 0)
{
re_assigning();
}
else
{
return;
}
}
}
};
//this is now outside the class..
//class declarations
Chromebook_slot slot1;
Chromebook_slot slot2;
//variables for rocker switches which will act for detecting chromebooks.
// in my final version, this will replaced by a photoresistor and laser.
slot1.rocker = 3;
slot2.rocker = 2;
Where the function re_assigning() is a separate function declared further in the code and just resets the slot as open for future use.
slot1.rocker = 3;
slot2.rocker = 2;
These are statements that cannot be at the top level of a C++ (or .ino) file. They need to be inside of a function. What's happening is the compiler is looking looking at the slot1 identifier through the lens of potential valid constructions. It sees an identifier, and about the only thing that could legally exist at this point in the code that starts with an identifier like that is some declaration, e.g. int a = 7;, or more abstractly some_type some_more_stuff. So it expects slot1 to be a type, which it isn't, hence the message.
If you want an assignment like those to happen early on in an Arduino program, the simplest thing you could do is put them in setup():
void setup() {
slot1.rocker = 3;
slot2.rocker = 2;
// ...
}
Or, you'd make these part of the Chromebook_slot's constructor, such that they could be given in slot1 and slot2's declaration:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value) {
rocker = rocker_init_value;
}
// ...
Or in a maybe less familiar but more proper form, using the constructor's initialization list:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value)
: rocker(rocker_init_value) {}
// ...
Once you have a constructor for Chromebook_slot, your variables can become:
Chromebook_slot slot1(3);
Chromebook_slot slot2(2);

accessing a vector in a function

I'm quite new to c++ and am not very good at understanding about references and pointers.
I'm making a project in Qt to book appointments in a salon and am currently trying to assign a stylist object to the stylist data member in the chair object.
The function below is to assign stylist to a particular chair. At the end of this function, if you print out the stylist name of the stylist in the chair it has been assigned, however outside of this function the value is not assigned. All the getters are returning a reference but the Calender vector, a vector of Week objects, is just called as it is a data member of the class holders. I am wondering if this is the issue but I thought using the [] operator meant that the vector value at that index was returned by reference.
void Holders::BookStylistToChair(int week, int day, float timeslot, stylist temp)
{
for (int i = 0; i < Calender[week].getaweek()[day].getaday()[timeslot].GetNumberOfChairsInslot(); i++) {
bool check = Calender[week].getaweek()[day].getaday()[timeslot].GetChairVector()[i].getoccupied();
if (check == false) {
Calender[week].getaweek()[day].getaday()[timeslot].GetChairVector()[i].SetStylist(temp);
Calender[week].getaweek()[day].getaday()[timeslot].GetChairVector()[i].Setoccupied();
break;
}
}
}
The Week class is shown below:
class Week {
private:
//A week full of 7 days
QVector<Day> AWeek;
public:
//CREATE DAYS IN A WEEK
void Create7days(int, int, int);
//Getter
QVector<Day>& getaweek() ;
};
The week class contains a getter getaweek, which returns a vector of objects of class day. Day contains
class Day {
private:
QString DayName;
// A day full of timeslots
QVector<Timeslot> ADay;
public:
//Create Timeslots
void CreateTimeSlot(int, int, int);
void setdayname(QString);
//Getter
QString getdayname();
QVector<Timeslot>& getaday() ;
};
The getters are all returning references but I'm unsure if they are correct because I haven't used const even though I know I probably should but I keep getting errors when I do I'm not sure how to include const references.
I hope this is enough information I'm sorry if it isn't.
Thank you

Keep getting out of bounds exception, don't know why?

I'm making a 3 dimensional tic tac toe game. The game is complete and works fine, however, the assignment demands that (for testing game situations) the program take in a file of integers that places pieces on the game board. It takes in the file from the Unix command line.
However, the game is supposed to run from start if no file is entered in command line. I'm getting an out of bounds exception and don't know why for the life of me. Any help would be greatly appreciated.
Portion of code for getting file and storing the integers:
public class Test {
static int board[][][] = new int[4][4][4];
static boolean ComputerMoved = false;
static int[] sums = new int[76];
static int n = 0;
public static void main(String[] args) throws FileNotFoundException {
//Method purpose is to look and see if there is a startup file given to
//initally setup the board. If not, plays an empty board and prompts the
//user for the first move.
Scanner scan = new Scanner(new FileInputStream(args[0]));
if (args.length > 0) {
int size = scan.nextInt();
for (int i = 0; i < size; i++) {
int level = scan.nextInt();
int row = scan.nextInt();
int column = scan.nextInt();
int value = scan.nextInt();
level = level % 4;
row = row % 4;
column = column % 4;
board[level][row][column] = value;
}
}
Hint: It appears that the out of bounds exception is coming not from your array, but rather your scanner. Could it be possible you don't have "enough" numbers to scan?

Reading and writing classes with pointers to binary files in c++

I've been trying to write some data to a binary file in c++ using fstream and most examples go like this:
#include <fstream>
class Person{
public:
int age;
char name[50];
}
int main(){
Person joe;
joe.age = 50;
strncpy(joe.name, "Joe Jones");
fstream file("filename.dat", ios_base::binary);
file.write((char*)joe, sizeof(joe));
file.close();
}
This works just as expected but the problem arises when I try to write a more complex structure, mainly one with pointers instead of the actual data.
class Person{
public:
int age;
int *friendsAges;
Person(int friends){
friendsAges = new int[friends];
}
}
When I write the data like before
Person joe(10);
/* Initialize rest of joe */
file.write((char*)joe, sizeof(joe));
the resulting file has 8 bytes of data, 4 for the age and 4 for the address of the friendsAges array or so it seems.
How could I go about writing the actual data that is stored in the array? I have also had this problem when my classes have other classes as members such as a Person having a Car or something like that.
For starters, add a method to your class that will perform the file I/O then you can just call it like so:
Person joe();
Person sally();
fstream file("filename.dat", ios_base::out | ios_base::binary);
joe.serialize(file, true);//writes itself to the file being passed in
sally.serialize(file, true); //write another class to file after joe
file.close();
Then later you could read that same file to populate the class instance:
fstream file("filename.dat", ios_base::in | ios_base::binary);
joe.serialize(file, false); //reads from file and fills in info
sally.serialize(file, false); //reads from file too
file.close();
The method in the class would look something like this:
Person::serialize(fstream &fs, bool bWrite)
{
int ages_length;
if (bWrite) {
fs.write(&age, sizeof(age));
ages_length = ...; //you need to know how long the friendsAges array is
fs.write(&ages_length, sizeof(ages_length)); //write the length to file
fs.write(&friendsAges[0], sizeof(int)*ages_length); //write the variable-sized array to file
fs.write(&name[0], sizeof(char)*50); //write a string of length 50 to file
}
else {
fs.read(&age, sizeof(age));
fs.read(&ages_length, sizeof(ages_length)); //read length of array from file
//TODO: you will need to malloc some space for *friendsAges here
fs.read(&friendsAges[0], sizeof(int)*ages_length); //read-in the variable length array
fs.read(&name[0], sizeof(char)*50); //this only works if string length is always fixed at 50
}
}

Unable to match current Date and time in Qt

I am writing a simple task planner and reminder using Qt which will play a sound file when the date and time of any given task matches with the the current date and time.
To implement this, I am running a QThread which checks the task in the list to see if any match the current time and if so, plays the sound file.
This id my original class:
class Task
{
public:
QString ta, desc;
QTime ti;
QDate da;
int pri, diff;
bool ala;
};
This is my Thread Class:
class AlarmCheck : public QThread
{
public:
void setTask(QList<Task>);
void run();
bool isRunning;
QString music;
QTime alarmOffset;
private:
QList<Task> list;
};
My Implementation:
void AlarmCheck::setTask(QList<Task> l)
{
list = l;
}
void AlarmCheck::run()
{
while(isRunning)
{
foreach(Task t, list)
{
if((t.da == QDate::currentDate()) && (t.ti == QTime::currentTime()) && t.ala)
{
Phonon::MediaObject *gaana =
Phonon::createPlayer(Phonon::MusicCategory,
Phonon::MediaSource(music));
gaana->play();
QMessageBox::information(NULL,
"Alarm!!!",
"The time has come for\n"
+ t.ta +
"\n Time to do it!");
gaana->stop();
}
qDebug("Curr = " + QTime::currentTime().toString().toAscii() + " Date = " + QDate::currentDate().toString().toAscii());
qDebug("Task = " + t.ti.toString().toAscii() + " Date = " + t.da.toString().toAscii());
}
sleep(1);
}
}
The thing is that the thread is running perfectly, but the if() condition inside the foreach() loop is never satisfied for some reason. I even checked the individual date/time/alarm setting (t.ala) using qDebugs (as you can see); they are all fine.
Your if statement requires that the date and time match exactly, down to the millisecond. It is unlikely that your loop will evaluate at this exact moment. If you want to maintain similar logic (processing tasks in a loop), you might try sorting them by "next task first" (or perhaps using a queue), then testing in your if statement if the current QDateTime is equal-to-or-greater than the task date/time of the first task.

Resources