Quiz program always evaluating answer to be wrong - c++

class Question{
protected:
int op1;
int op2;
string operate;
public:
Question();
};
class generateRandomQuiz:Question{
public:
generateRandomQuiz();
int getp1();
int getp2();
string getOp();
};
class checkAnswer:generateRandomQuiz{
private:
int Ans;
public:
checkAnswer(int ans);
};
Question::Question()
{
op1=23;
op2=12;
operate="/";
}
generateRandomQuiz::generateRandomQuiz():Question()
{
op1=rand()%50;
op2=rand()%50;
string s="+-/*";
int n=rand()%4;
operate=s[n];
}
int generateRandomQuiz::getp1()
{
return op1;
}
int generateRandomQuiz::getp2()
{
return op2;
}
string generateRandomQuiz::getOp()
{
return operate;
}
checkAnswer::checkAnswer(int ans):generateRandomQuiz()
{
Ans=ans;
string operate=getOp();
int op1=getp1();
int op2=getp2();
if (operate=="+")
{
if (op1+op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
if (operate=="-")
{
if (op1-op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
if (operate=="*")
{
if (op1*op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}if (operate=="/")
{
if (op1/op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
}
int main()
{
cout<<"This quiz is about evaluating an expression which is being generatedrandomly"
<<endl;
generateRandomQuiz Q;
int answer;
int op1=Q.getp1();
int op2=Q.getp2();
string opr=Q.getOp();
cout<<"What is: "<<op1<<op2<<op2<<"=?"<<endl;
cin>>answer;
checkAnswer A(answer);
system("PAUSE");
return 0;
}
I am writing a program which generates a quiz randomly and asks the user for an answer answer like this: What is : 15 / 43 = ? The operator and numbers are randomly generated.But when i givw the correct answer,even then the comment for the wrong answer is printed.I have written conditions quite clear.Can someone please point it out?thanks

To check the answer you are relying on the fact that checkAnswer inherits from generateRandomQuiz.
But when you actually check the answer, you use a different instance than the random generated quiz, so you cannot get the generated quiz by doing stuff like int op1=getp1();.
By doing this you will get default constructed values only, and since your constructor does the randomizing, you will get a different question altogether. So the checking mechanism is right, its just checking a different question. I suggest you rethink your code structure, it looks very awkward.

Related

i can't get an output from this

#include<iostream>
using namespace std;
class stack
{
int size=10;
int stack[size]={0}, value=0, top;
top=size;
public:
void push(int v)
{
if(top==0)
cout<<"\nstack is full\n";
else
{--top;
stack[top]=v;}
}
void pop()
{
if(top==size)
cout<<"\nstack is empty\n";
else
{top++;
stack[top];
stack[top-1]=0;
}
}
void display()
{
if(top==size)
cout<<"\nstack empty\n";
else
{
for(int i=top;i<size-1;i++)
{
cout<<stack[i];
}
}
}
};
int main()
{
stack s;
char t;
int value,ch;
do
{
cout<<"\n1.push\n";
cout<<"\n2.pop\n";
cout<<"\n3.display\n";
cout<<"enter choice:\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nenter the value to be pushed\n";
cin>>value;
s.push(value);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
default:
cout<<"\nwrong choice\n";
}
cout<<"\ndo u want to retry\n";
cin>>t;
}while(t=='y' || t=='Y');
return 0;
}
Simplest fix to errors occurring is changing int size=10; to static const int size=10;.
After this, apart from occurring warning with stack[top]; being empty statement, there is logical error in display loop in for(int i=top;i<size-1;i++) where it should be either for(int i=top;i<size;i++) or for(int i=top;i<=size-1;i++).
As answered by Tomáš Zahradníček, you need to fix a few things to have your code compile (using -std=c++11).
I used for(int i=top; i<size; ++i) in the display method. I also add that your pop method could simply do top++; without overwriting the stack.
Anyways, regarding your problem of nothing being printed on cout : you obviously tried with 1 item pushed in the stack, but not with 2, which would have pointed to faulty line (the for loop).

searching method using certain keyword to give desired output

here i want enter the patient data, and then i want to be able to give output after key in the id, this means that i use searching method, here i use linear search. i use array, to save the patient data, such as name and age. so in pharmacy department i want to be able to search the patient data before approving giving medicine.
#include<iostream.h>
int linear(int patient[],int size,int key);
int linear(int patient[],int size,int key) {
int i;
for(i=0;i<2;i++) {
if(key==patient[i].id) {
return i;
}
}
return -1;
}
void main() {
int i=0;
int size=2;
struct patientRecord {
char name[20];
int id,age;
int *patient;
};
patientRecord patient[i];
int choice;
cout<<"Welcome to Hospital Sejahtera\n";
cout<<"Please enter your choice:";
cout<<"1.Patient Registration\n2.Pharmacy\n3.Doctor Appoinment";
cin>>choice;
if(choice==1) {
for(i=0;i<2;i++) {
cout<<"Please enter patient name";
cin>>patient[i].name;
cout<<"Please enter patient id";
cin>>patient[i].id;
cout<<"Please enter patient age";
cin>>patient[i].age;
}
} else if(choice==2) {
int i;
for(i=0;i<2;i++) {
cout<<"Enter the patient id to search:";
cin>>patient[i].id;
linear(patient,size,patient[i].id);
cout<<"Location at index:";
cout<<endl;
}
}
}
i would be glad if you all can point out my mistake. im still learning. please help.
You might get a compile warning here that the variable size is not used.
You should check out what that is and where it should go.
int linear(int patient[],int size,int key) {
int i;
for(i=0;i<2;i++) {
if(key==patient[i].id) {
return i;
}
}
return -1;
}

C++ strange "format" of output string

I am writing a C++ applications that is working with files. I have implemented standard operations like writing and reading from the file, some search functions, etc.
After doing some operations, my output strings come in a very strange way. For example the text "Address -", comes as "?п&&..&":
Is there any buffer in C++ that could be full by the file operations and it is doing this output so i need to empty it or clean it?
Edit: The problem appeared when I write a functions that is reading the records from my file, choosing some of them due to user criteria and then sorting them.
Here is my code:
Stucture:
struct Appartament
{
char address[50];
char telephoneNumber[20];
char view[10];
double price;
double distanceFromCenter;
int roomCount;
};
Function working with the file:
//Search by room count and order by price (rising)
void AdvanceSearch()
{
clrscr();
Appartament currentRecord;
int recordsCount=0;
fstream currentFile("Records.dat",ios::binary|ios::in);
if(!currentFile)
{
cout<<"Error - the file could not be opened."<<endl;
return;
}
else
{
//Array with apartments records
Appartament CurrentRecords[MaxRecords];
currentFile.seekg(0L,ios::end);
long int length=currentFile.tellg();
currentFile.seekg(0L,ios::beg);
int isAppartamentFound=0;
if(length==0)
{
cout<<"The file is empty."<<endl;
return;
}
else
{
int userRoomCount;
do
{
clrscr();
cout<<"Enter apartment room count - ";
cin>>userRoomCount;
}while(userRoomCount<0);
clrscr();
cout<<endl<<"Apartments with "<<userRoomCount<<" rooms order by price:";
currentFile.read((char*)(&currentRecord),sizeof(Appartament));
while(!currentFile.eof())
{
if(currentRecord.roomCount==userRoomCount)
{
CurrentRecords[recordsCount]=currentRecord;
recordsCount++;
isAppartamentFound=1;
}
currentFile.read((char*)(&currentRecord),sizeof(Appartament));
}
currentFile.close();
}
if(isAppartamentFound==0)
{
cout<<endl<<"There are no matches!"<<endl;
}
else
{
//If only one apartment is found
if(recordsCount==1)
{
cout<<endl;
ShowRecord(currentRecord);
}
else
{
//Sort the records
Appartament tempApartament;
int isChangeMade=1;
for(int index=0;index<recordsCount;index++){
//ShowRecord(CurrentRecords[index]);
}
while(isChangeMade==1)
{
isChangeMade=0;
for(int index=0;index<recordsCount-1;index++)
{
if(CurrentRecords[index].price>CurrentRecords[index+1].price)
{
isChangeMade=1;
tempApartament=CurrentRecords[index];
CurrentRecords[index]=CurrentRecords[index+1];
CurrentRecords[index+1]=tempApartament;
}
}
}
for(index=0;index<recordsCount;index++)
{
ShowRecord(CurrentRecords[index]);
}
}
}
}
}
Function for showing a record:
void ShowRecord(Appartament Record)
{
cout<<"Apartment Information"<<endl;
cout<<"The address is - "<<Record.address<<" and it is only "<<Record.distanceFromCenter<<" miles away from the center."<<endl;
cout<<"The price is "<<Record.price<<" $ for "<<Record.roomCount<<" rooms with "<<Record.view<<" view."<<endl;
}
Тhis is possible output:
I have run my program on other machine with other version of Borland and it is working perfectly. That's why the questions is what is wrong with mine compiler :?

C++ Copy one struct value to other

I have a simple structure:
struct Appartament
{
char address[50];
char telephoneNumber[20];
char view[10];
double price;
double distanceFromCenter;
int roomCount;
};
I have some records written in a file. Now, I want to read all records from the file and to get only this who have roomCount smaller then a number (user input). This is easy, but the records should be displayed sorted by price. That's way I have to put them in a array and after that to sort them.
I have some problems and I believe that they are because I am not copping the structures well.
I have try different ways:
strcpy(CurrentRecords[index].address,currentRecord.address);
strcpy(CurrentRecords[index].telephoneNumber,currentRecord.telephoneNumber);
strcpy(CurrentRecords[index].view,currentRecord.view);
CurrentRecords[index].price=currentRecord.price;
CurrentRecords[index].distanceFromCenter=currentRecord.distanceFromCenter;
CurrentRecords[index].roomCount=currentRecord.roomCount;
or
memcpy(CurrentRecords[index],currentRecord,sizeof(Appartament));
and
CurrentRecords[index]=currentRecord
but nothing works...
EDIT: Here is the my code - "nothing works" refers to something like endless loop.
void AdvanceSearch()
{
clrscr();
Appartament currentRecord;
fstream currentFile("Records.dat",ios::binary|ios::in);
if(!currentFile)
{
cout<<"Error - the file could not be opened."<<endl;
return;
}
else
{
//Array with apartments records
Appartament CurrentRecords[MaxRecords];
currentFile.seekg(0L,ios::end);
long int length=currentFile.tellg();
currentFile.seekg(0L,ios::beg);
int isAppartamentFound=0;
if(length==0)
{
cout<<"The file is empty."<<endl;
return;
}
else
{
int userRoomCount;
do
{
clrscr();
cout<<"Enter apartment room count - ";
cin>>userRoomCount;
}while(userRoomCount<0);
clrscr();
cout<<endl<<"Apartments with "<<userRoomCount<<" rooms order by price:";
currentFile.read((char*)(&currentRecord),sizeof(Appartament));
int index=0;
while(!currentFile.eof())
{
if(currentRecord.roomCount==userRoomCount)
{
/*
strcpy(CurrentRecords[index].address,currentRecord.address);
strcpy(CurrentRecords[index].telephoneNumber,currentRecord.telephoneNumber);
strcpy(CurrentRecords[index].view,currentRecord.view);
CurrentRecords[index].price=currentRecord.price;
CurrentRecords[index].distanceFromCenter=currentRecord.distanceFromCenter;
CurrentRecords[index].roomCount=currentRecord.roomCount;
*/
memcpy(CurrentRecords[index],currentRecord,sizeof(Appartament));
//CurrentRecords[index]=currentRecord;
index++;
isAppartamentFound=1;
}
currentFile.read((char*)(&currentRecord),sizeof(Appartament));
}
currentFile.close();
}
if(isAppartamentFound==0)
{
cout<<endl<<"There are no matches!"<<endl;
}
else
{
//If only one apartment is found
if(sizeof(CurrentRecords)/sizeof(Appartament)==1)
{
cout<<endl;
ShowRecord(currentRecord);
}
else
{
//Sort the records
Appartament tempApartament;
int isChangeMade=1;
while(isChangeMade==1)
{
isChangeMade=0;
for(int index=0;index<(sizeof(CurrentRecords)/sizeof(Appartament))-1.0;index++)
{
if(CurrentRecords[index].price>CurrentRecords[index+1].price)
{
isChangeMade=1;
CopyApartament(tempApartament,CurrentRecords[index]);
CopyApartament(CurrentRecords[index],CurrentRecords[index+1]);
CopyApartament(CurrentRecords[index+1],tempApartament);
}
}
}
for(int index=0;index<sizeof(CurrentRecords)/sizeof(Appartament)-1.0;index++)
{
ShowRecord(CurrentRecords[index]);
}
}
}
}
}
void CopyApartament(Appartament RecordOne,Appartament RecordTwo)
{
/*
strcpy(RecordOne.address,RecordTwo.address);
RecordOne.distanceFromCenter=RecordTwo.distanceFromCenter;
RecordOne.price=RecordTwo.price;
RecordOne.roomCount=RecordTwo.roomCount;
strcpy(RecordOne.telephoneNumber,RecordTwo.telephoneNumber);
strcpy(RecordOne.view,RecordTwo.view);
*/
RecordOne=RecordTwo;
}
Note: I thought that my problem is the copying because I have not know how to do this.
CurrentRecords[index]=currentRecord;
That copies an entire structure and should work as expected.
Are you sure you are sorting correctly?
I don't see any particularly good reason to have explicit copying of the data anywhere. I think I'd do something like this:
std::vector<Apartment> get_apts(int max_rooms) {
std::vector<Apartment> apts;
std::copy_if(file.begin(), file.end(), std::back_inserter(apts),
[max_rooms](Apartment const &a) {
return a.roomCount < max_rooms;
});
std::sort(apts.begin(), apts.end(),
[](Apartment const &a, Apartment const &b) {
return a.price < b.price);
});
return apts;
}

Two questions of c++ which just change a little,however very different answers

Recently I do a exercise about algorithm with c++. Exercise in here:poj
I find two very confused questions.
I write a class MAZE and there are three primary functions in MAZE,they are
int left_path();int right_path();int mini_path();
and a function to print the answers:
void display(){
cout<<left_path()<<" "<<right_path()<<" ";
cout<<mini_path()<<endl;
}
the program can work correctly.As we see the function display() can be easy;
I write like this
void display(){
cout<<left_path()<<" "<<right_path()<<" "<<mini_path()<<endl;
}
just one change ;however the program can't work,it like loop infinitely.
following is the other question:
the function mini_path's frame like this
int maze::mini_path(){
ini();
queue<pair<int,int> > q;
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
int t=...;
if(E){
return t;
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
}
return -1;
}
if there is "return -1" in the end ,the function works right,else the function return random big number.
The program is in only one file and i use the gun compiler.
I don't show the total codes,because i think nobody wants to see them.I just want to ask what problems may lead above strange behaviors.
source code(simplified for question2):
typedef enum {LEFT=-1,RIGHT=1,UP,DOWN} direction;
ifstream fin("file_test3.txt");
class maze{
public:
maze(){input();}
int mini_path();
void input();
void display(){
cout<<mini_path()<<endl;
}
private:
bool is_not_dest(){
return !(x==d_x && y==d_y);
}
void ini_dir()
{
if(e_x==0) dir=DOWN;
else if(e_x==height-1) dir=UP;
else if(e_y==0) dir=RIGHT;
else dir=LEFT;
}
void ini(){
x=e_x;
y=e_y;
path_lenth=1;
ini_dir();
}
direction dir,d;
int width,height,maze_map[40][40],path_lenth;
int x,y,e_x,e_y,d_x,d_y;
};
void maze::input()
{
fin>>width>>height;
char sym;
for(int i=0;i<height;++i)
for(int j=0;j<width;++j){
fin>>sym;
if(sym=='#')
maze_map[i][j]=1;
else if(sym=='.')
maze_map[i][j]=0;
else if(sym=='S'){
maze_map[i][j]=-1;
e_x=i;
e_y=j;
}
else {
maze_map[i][j]=-2;
d_x=i;
d_y=j;
}
}
}
int maze::mini_path()
{
ini();
queue<pair<int,int> > q;
if(dir==LEFT) {maze_map[x][--y]=2;}
else if(dir==RIGHT) {maze_map[x][++y]=2;}
else if(dir==UP) {maze_map[--x][y]=2;}
else {maze_map[++x][y]=2;}
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
x=tmp.first;
y=tmp.second;
int t=maze_map[x][y]+1;
if((x==d_x && (y-d_y==1 || y-d_y==-1)) ||(y==d_y && (x-d_x==1||x-d_x==-1))){
return t;
}
if(maze_map[x-1][y]==0){
maze_map[x-1][y]=t;
q.push(make_pair(x-1,y));
}
if(maze_map[x+1][y]==0){
maze_map[x+1][y]=t;
q.push(make_pair(x+1,y));
}
if(maze_map[x][y-1]==0){
maze_map[x][y-1]=t;
q.push(make_pair(x,y-1));
}
if(maze_map[x][y+1]==0){
maze_map[x][y+1]=t;
q.push(make_pair(x,y+1));
}
}
return -1;
}
main()
{
int n;
fin>>n;
while(n-- >0){
class maze m;
m.display();
}
}
I see it! Can you see it? :)
#include <iostream>
using namespace std;
int foo(int bar)
{
cout << bar << endl;
return bar;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << foo(1) << foo(2) << foo(3) << endl;
return 0;
}
The output:
3
2
1
123
regarding question1:
The order in which the functions are called will be different.
the first solution will call them in following order:
right_path
left_path
mini_path
the second solution results in following order:
mini_path
right_path
left_path
so the solution you probaly want is:
void display(){
cout<<left_path()<<" ";
cout<<right_path()<<" ";
cout<<mini_path()<<endl;
}
There is not enough info to answer the first question; both codes are equivalent.
[Edit:Check other answers. Anyway, both codes should be equivalent: you have bugs in your code.]
About the second question, I guess that that "return -1" marks "no possible path" in your maze, that's why, when you remove it, your program stops working.
In the maze problem, a backtracking algorithm moves square by square. When from a square there is no possible path, this square must be marked as no path.