You could try the scanf function...
int h,m;
scanf("%d:%d",&h,&m);
You can enter the time as xx:xx
You could try the scanf function...
int h,m;
scanf("%d:%d",&h,&m);
You can enter the time as xx:xx
Thanks Duoas!
And everyone who tried to help!
I have changed that gets() function then itself(See post #6, reply to Salem). I just wanted to know if gets() gets into fstream's way ;)
I have added the binary mode too into open() .
I didn't get you(Duoas) the first time you told that.I thougt you were asking me to open a file before trying to read and write from it!!!
I was not able to use that statement Duoas asked me to.
compiler couldnot recognize std.
I tried using the statement using namespace std;
and got error : declaration syntax error.
The IDE does not recognize using
as a keyword either.
Though I fixed the problem by first taking the value of sizeof into an integer variable and then passing this variable inside seekg().(How it worked I dont know! Maybe it helped in type conversion).
Opening file in binary mode was particularly useful to read the objects from file
(or is it unserializing the objects from the file?)
The size of all objects were not the same in text mode.(Why? I don't know)
In short, the problem is solved. And I would be glad if someone would help understand how it got solved!!! :-/
Please try to answer the questions I've asked in this post when you explain what has really happened!!
@Duoas
I'm sorry I got a bit angry at you!
One more thing the ios::fail flag is set after the write function call. But ios::bad is not set.
@Duoas
"Stock.txt" exists and has 1 object in it.
I wrote it by hiding the read line mentioned in the question and my last post.
How many times should I say that?:@
That's the reason I'm asking this question in this thread. :S
Else I would have assumed that I have messed up with the syntax or logic somewhere!!!
@ Salem
The gets() function has nothing to do with reading and writing into a file I guess. Anyway, I have changed it to cin, if its a bad style to use C functions. [I'm curious to know if there is indeed something awful with that function!]
This is driving me nuts. I'm stuck because I cannot go ahead with my program without writing this into the file.
Sorry i forgot to mention I am opening the file in the main() function stfile.open("stock.txt",ios::in|ios::out);
And those tellp() functions I used just to see if the file is being actually written into the file.
What baffles me is that the object is being written into the file when the statement that reads an object from file (line 26 in the snippet given in question) is removed ( making it a comment).
hey! are you sure you are not lying about your name???:icon_eek:
Its a good idea to use a screen name instead of your real name.
But I don't think its nice to tell people that the screen name is your real name!!!
Anyway, welcome abroad sis!!!:)
In the following code, the object is not being written into file in line 30 stfile.write((char*)this,sizeof(item));
When line 26 : stfile.read((char*)&ob,sizeof(item));
is hidden the object is written into the file.
Please help!!!
fstream stfile;
class item
{
int code;
char name[25];
int price;
int qty;
public:
int getcode()
{
return code;
}
void GetNew()
{
// cout<<"\nENTER THE CODE"; //Unhide this when
// cin>>code; //entering first iteminto the file
cout<<"\n ENTER THE ITEM NAME";
gets(name);
cout<<"\n ENTER THE PRICE";
cin>>price;
cout<<"\n ENTER STOCK";
cin>>qty;
item ob;
stfile.seekg(-1*sizeof(item),ios::end);
stfile.read((char*)&ob,sizeof(item));
code=ob.getcode();code++; //hide these three
stfile.seekp(0,ios::end); //lines when entering
cout<<stfile.tellp()<<endl; //first iten into the file
stfile.write((char*)this,sizeof(item));
cout<<stfile.tellp();
return ;
}
void show()
{ cout<<"\ncode " <<code
<<"\nname "
<<name
<<"\n price"
<<price
<<"\n quantity"
<<qty;
}
};
void ShowItem(int c)
{
stfile.seekg(0,ios::beg);
stfile.clear();
while(!stfile.eof())
{item ob;
stfile.read((char*)&ob,sizeof(item));
if(stfile.eof())
{perror("search"); break;}
if(ob.getcode()==c)
{ ob.show();break; }
}
}
Thanks for taking pain to explain!!!
flushing works.
could you please explain how and why it works?
i posted this problem in C++ forum and people told me its impossible.
I'm using a very old version of C++ and most of its features are very similar to C.
So i thought maybe you people will understand what the problem is....
In the following code, getch() is executed before the file is displayed.
void ReadFile()
{ char fname[13],ch;
cout<<"Enter filename : ";
cin>>fname;
strcat(fname,".mth");
temp.open(fname,ios::in|ios::nocreate);
if(!temp)
{ cout<<"File does not exist!!!";
getch(); return;
}
temp.get(ch);
while(!temp.eof())
{ cout.put(ch);
temp.get(ch);
} temp.close();
getch();
}
you can find the thread i've posted in C++ forum at
http://www.daniweb.com/forums/thread103115.html
i've posted there the exe file i got after compiling the program containing this function and how to get this error un that program.
The file is opened and read!
only the program doesnot wait after displaying the file, it goes on with displaying the menu.
i've attached my exe file after zipping it!
if you are so much sure i'm lying, u can try executing it.:ooh:
First choose 1 in menu, type anything you like, press ctrl+G after that and save the file when prompted.
then choose 2, the menu is displayed along with the file, without waiting for getch().
does it getch() after the file is displayed???
in the following code, getch() is executed before the file is displayed.!
whats wrong? how can i correct this?
void ReadFile()
{ char fname[13],ch;
cout<<"Enter filename : ";
cin>>fname;
strcat(fname,".mth");
temp.open(fname,ios::in|ios::nocreate);
if(!temp)
{ cout<<"File does not exist!!!";
getch();
return;
}
temp.get(ch);
while(!temp.eof())
{ cout.put(ch);
temp.get(ch);
}
temp.close();
getch();
}
i've made the final draft of the program its the same as the one posted in post #15
only i've changed the return type of main to int and added the statement
return 0;
at the end.
i feel that it has improved since i've started this thread.
Thanks, everyone who has helped!
And Happy New Year to all.
ok!
now what about the comments?
is it enough?should i add more? delete some? modify some?
That Programming tips were quiet useful!
But i couldnot understand certain terms in it.
Could someone explain to me what it means?
1. "telephone test"
2. off-by-one error
oh! i too found the file too big to handle.
but we are not supposed to split the program code.
you see, its not in our syllabus!
oh! sorry!
i didn't see your last post!
So you mean to say,
int main()
is the standard code???
i'm using an old version of C++.
its just like C. Only difference - you can have classes in this.
And about the non-standart stuff .
i didn't find anything to that effect in Salem's post.(if you are reffering to post no. 14)
I've made the changes you people asked me to make ( I hope!:) ). If its not enough please tell.
I have also made some changes to the program.
In addition to commenting please tell me if there is something that i can improve upon in the program, without greatly changing the structure of the program.
Please find attached the program "file1.cpp".
/* Expression Evaluation Notebook
Program to read text from keyboard and write it into a file, after
evaluating all simple mathematical expressions in the text.*/
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
/**********************Definitions of Data Structures Used*********************/
union element //used to store parsed elements
{ char sym; //for symbol
int ival; //for integer
float fval; //for float
};
struct info //information part of stack/queue
{ element el; //element
char flag; //flag to show type of element
//0 for integer
//1 for float
//2 for symbol
//-5 for underflow (in queue and stack)
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
};
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
//Defining Global objects and variables
fstream temp;
Queue expr;
int fail;
/***************************Function declarations******************************/
void intro();
void menu();
char symb(char);
int insert();
void post_convert();
int evaluate();
int expression();
void NumberToFile(info);
void convert(long int);
void WriteFile();
void ReadFile();
/****************************End of declarations******************************/
/*******************************Main Function**********************************/
void main()
{ intro();
menu();
}
/********************************End of Main***********************************/
/************************Other Function definitions****************************/
//function for welcome screen
void intro()
{ clrscr();
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t"
<<"Expression Evaluating Notebook"
<<"\n\t\t\t______________________________";
getch();
clrscr();
cout<<"\n\n\n\n\n\n\n\n\n\n\t\t"
<<"Submitted by"
<<"\n\n\t\t\tGeorge Sebastian"
<<"\n\n\t\t\t"
<<"Class XII (2007-08)"
<<"\n\n\t\t\t"
<<"Kendriya Vidyalaya No:1, Kasaragod"
<<"\n\n\n\n\n\n\n\n\n\t\t"
<<"Submitted to"
<<"\n\n\t\t\t"
<<"Mr. Mahesh Chand Pal"
<<"\n\n\t\t\t"
<<"PGT (Computer Science)"
<<"\n\n\t\t\t"
<<"Kendriya Vidyalaya No:1, Kasaragod";
getch();
}
//Menu screen
void menu()
{ clrscr();
int choice;
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tMenu:"
<<"\n\n\n\t\t\t1.Write a new file"
<<"\n\n\n\t\t\t2.Read an existing file"
<<"\n\n\n\t\t\t3.Add to an existing file"
<<"\n\n\n\t\t\t4.Delete an existing file"
<<"\n\n\n\t\t\t5.Exit"
<<"\n\n\nEnter your choice(1-5) : ";
cin>>choice;
switch(choice)
{ case 1 : temp.open("temp.mth",ios::trunc|ios::out);
WriteFile();
break;
case 2 : ReadFile();
break;
case 3 : temp.open("temp.mth",ios::app|ios::out);
WriteFile();
break;
case 4 : char fname[13];
cout<<"Enter filename";
cin>>fname;
strcat(fname,".mth");
remove(fname);
break;
case 5 : return;
default: break;
}
menu();
}
//function to read file
void ReadFile()
{ char fname[13],ch;
cout<<"Enter filename : ";
cin>>fname;
strcat(fname,".mth");
temp.open(fname,ios::in|ios::noreplace);
if(!temp)
{ cout<<"File does not exist!!!";
getch();
menu();
return;
}
temp.get(ch);
while(!temp.eof())
{ cout.put(ch);
temp.get(ch);
}
getch();
}
//function to write into file
void WriteFile()
{ clrscr();
char ch,fname[13];
cin.get(ch);
while(ch!=7) //Read till ^G is encountered
{ if(ch=='=')
{ cin.get(ch);
//If '==' is encountered, evaluate expression
if(ch=='=')
fail=expression();
else //if its a single '=', put into file
temp.put('=');
if(fail) //if expression evaluation fails
cout<<"Error : Expression syntax error!!";
}
else //if no '=' is encountered, just write to file
temp.put(ch);
cin.get(ch);
}
//Saving file
cout<<"Save file?(y/n)\n";
cin>>ch;
if(ch=='y'||ch=='Y')
{ cout<<"Give the filename(max. 8 characters) : ";
cin>>fname;
strcat(fname,".mth");
rename("temp.mth",fname);
}
else
remove("temp.mth");
}
//function to convert infix expression to postfix and evaluates
int expression()
{
//to read expression, parse it and insert to queue
fail=insert();
if(!fail)
{ post_convert(); //convert infix to postfix
fail=evaluate();
}
if(fail)
return -1;
return 0;
}
//function to parse expression and insert into queue
int insert()
{ int ctr=0,sign=1,MinusFlag=1; //flags to handle parantheses
//and unary minus
float factor;
char in[81];
info inf={ 0,0};
for(int i=0;i<81&&in[i-1]!=';';i++)
{ cin.get(in[i]); //read the expression without
if(isspace(in[i]))i--; //white spaces
}
for(i=0;in[i]!=';';i++) //parsing
{
if(symb(in[i]))
{
//change sign for unary minus
if(in[i]=='-'&&MinusFlag)
{ sign*=-1;
inf.flag=0;
continue;
}
else sign=1; //if symbol is not unary minus,
//reset 'sign' to 1
//check if operators and operands
//are entered alternately
if(symb(in[i])&&(symb(in[i+1])||in[i+1]==';'))
if(in[i+1]!='('&&in[i+1]!='-'&&in[i]!=')')
{ cout<<"Error!! too many operators!!!";
return -1;
}
if(in[i]=='(')
{ ctr++;
//If there is no symbol before '(',
//then multiply by default
if(inf.flag!=2&&i!=0)
{ inf.el.sym='*';
inf.flag=2;
expr.push(inf);
}
}
else if(in[i]==')')
ctr--;
if(ctr<0) //check if parantheses are balanced
{ cout<<"Error!!! More right paranthesis!!!";
return -1;
}
if(in[i+1]=='-') MinusFlag=1;
inf.flag=2;
inf.el.sym=in[i];
expr.push(inf);
}
else if(isdigit(in[i]))
{ MinusFlag=0;
//if first digit of a number, reset inf
if(symb(in[i-1])||i==0)
{ inf.flag=0;
inf.el.fval=0.0000000;
inf.el.ival=(int)(in[i]-'0')*sign;
}
else if(inf.flag) //if float
{ factor/=10; //decrement the place value
//of last digit
inf.el.fval+=(in[i]-'0')*factor*sign;
}
else //if integer
inf.el.ival=10*inf.el.ival+(int)(in[i]-'0')*sign;
if(symb(in[i+1])||in[i+1]==';')
expr.push(inf);
}
else if(in[i]=='.') //if '.' is encountered, set flag to float
{ inf.el.fval=(float)inf.el.ival;
inf.flag=1; //INPUT is float type
factor=1; //Reset the place value
//of last digit added
if(symb(in[i+1])||in[i+1]==';')
expr.push(inf);
}
}
//if more left parantheses, balance with
//right parantheses in the end of expression
if(ctr>0)
while(ctr)
{ info inf={')',2};
expr.push(inf);
ctr--;
}
return 0;
}
//function to set the precedence order
char symb(char c)
{ switch(c)
{ case '^':return 9;
case '/':return 8;
case '*':return 8;
case '+':return 7;
case '-':return 7;
case '(':return -1;
case ')':return 1;
default :return 0;
}
}
//function to convert infix to postfix
void post_convert()
{ Queue temp;
Stack symbols;
info psym,pexp={'(',2};
symbols.push(pexp);
while(pexp.flag!=-5) //Till the end of expr queue
{ pexp=expr.pop();
if(pexp.flag==2)
{ psym=symbols.peek();
while((symb(psym.el.sym)>=symb(pexp.el.sym))
&&pexp.el.sym!='(')
{ psym=symbols.pop(); //push all operators of
temp.push(psym); //greater precedence
psym=symbols.peek(); //into expr
}
if(pexp.el.sym==')') //remove '(' from the
symbols.pop(); //symbols stack
else
symbols.push(pexp);
}
else if(pexp.flag==-5) //when elements in queue ends
{ psym=symbols.pop();
while(psym.el.sym!='(') //till the last element
//in symbols stack
{ temp.push(psym);
psym=symbols.pop();
}
}
else //else pexp is operand
temp.push(pexp);
}
expr=temp; //now expr holds the postfix expression
}
//function to evaluate the postfix expression
int evaluate()
{ Stack eval;
info pexp,op1,op2,res;
pexp=expr.pop();
do
{ if(pexp.flag==1||pexp.flag==0) //if element is a number
eval.push(pexp);
else if(pexp.flag==2)
{ op2=eval.pop();
op1=eval.pop();
if(op1.flag||op2.flag) //if op1 or op2 is float type
res.flag=1; //the result is float
//if there is no element in stack
else if(op1.flag==-5)
cout<<"Too less operands";
else
res.flag=0;
switch(pexp.el.sym) //do the operation
{ case '+' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '-' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '*' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '/' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
break;
default :cout<<"\nError!!in eval";ret
also please tell me which of the comments I should remove - atleast some of them, if there are many(so that I may know what sort of comments is to be retained and what is to be removed!).
@ dubeyprateek
could you please explain what is to be written in "parameters" in your comment on functions.
Should I comment using the format
Method Name::
Parameters::
Return::
Purpose::
all the functions in my program.
@Narue
could you please illustrate the difference between the "why" comment and the "what" comment!
Please help me in self documenting the program below.
All you have to do is, take a quick glance at the following code to see if you can understand what each part is doing. If you have any difficulty in understanding(at a quick glance that is!), please tell me, so that I can add a comment.
Also tell me if I need to change the order in which I defined the functions and classes to enhance readability!
I've already posted this question once at
http://www.daniweb.com/forums/thread102405.html
I was asked to make a lot of changes so I closed the thread, made the changes and is reposting the question.
/* Expression Evaluation Notebook
Program to read text from keyboard and write it into a file, after
evaluating all simple mathematical expressions in the text.* /
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<ctype.h>
/**********************Definitions of Data Structures Used*********************/
union element //used to store parsed elements
{ char sym; //for symbol
int ival; //for integer
float fval; //for float
};
struct info //information part of stack/queue
{ element el; //element
char flag; //flag to show type of element
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
};
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
//Defining Global objects and variables
fstream temp;
Queue …
u can make it faster by incrementing counter by 2 when divisibilty by 2 fails.
u can further accelerate, by avoiding checking multiples of numbers already checked.(sieve of Eratosthenes)
Read sth about it at
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
also,
http://en.wikipedia.org/wiki/Primality_test
will help.
and...
personally, i feel checking till n/2 will be more efficient than sqrt(n). because sqrt(n) may take more steps.
u can also update the upper limit during each iteration
as
for (i=3;i<=n/i;i++)
ok! i'll close this thread and repost the program after i've documented it properly!!!
Please help me in self documenting the program below.
All u have to do is, take a quick glance at the following code to see if u can understand wat each part is doing. If u have any difficulty in understanding(at a quick glance that is!), pls tell me so that i can add a comment.
Also tell me if i need to change the order in which i defined the functions and classes to enhance readability!
/**********************Definitions of Data Structures Used*********************/
union element
{ char sym;
int ival;
float fval;
};
struct info
{ element el;
char flag;
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
};
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
//Defining Global objects and variables
fstream temp;
Queue expr;
int exp_flag;
/***************************Function declarations******************************/
char symb( char);
void display(Queue);
int insert();
void post_convert();
int evaluate();
int expression();
/****************************End of declarations******************************/
/*******************************Main Function**********************************/
void main()
{ clrscr();
temp.open("temp.mth",ios::out|ios::in);
char ch;
cin.get(ch);
while(ch!=7)
{ exp_flag=0;
if(ch=='=')
{ cin.get(ch);
if(ch=='=')
exp_flag=expression();
else
temp.put('=');
if(exp_flag)
cout<<"Error : Expression syntax error!!";
}
else
temp.put(ch);
cin.get(ch);
}
getch();
}
/********************************End of Main***********************************/
/************************Other Function definitions****************************/
int expression() //converts infix expression to postfix and evaluates
{ exp_flag=0;
int fail=insert();
cout<<"return frm insert()";
if(fail)return -1;
post_convert();
cout<<"\nreturn from post_convert()";
fail=evaluate();
cout<<"\nreturn from evaluate()"<<fail;
if(fail)
{ char …
Sorry! The prblem was not with the change in input.
I messed up with the way -ve numbers r handled and the way infix is converted to postfix.
in file.cpp
line 250:'>' should be replaced by '>='
line169:the statement MinusFlag=0; need to be added.
anyway! Thanx for trying to help me!!!
Especially Ancient Dragon and Walt P!!!
weird, division works!!!
==34/2;
gives the output 17
but nothing else does!
but when i use >> operator i cannot read wat comes after a blank space!
i want to read everythin in an expression, ignoring the white spaces!
like
== 12-8;
and ==12 -
8 ;
should evaluate to same result.
sorry! i forgot to mention!
i've added some cout statements in between the "file.cpp" file to site the error!
i found that that in line 345 in function evaluate(), the if statement is being executed.
it might mean there's some error in
I couldnot pin point the error till now!
Also, in "file.cpp"
to stop enterin into file, u got to press ctrl+g.
but getline reads whole line. i cannot ignore spaces with it.
with cin.get i can ignore spaces...
PROGRAM CODE OF "expeval.cpp"
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<ctype.h>
/**********************Definitions of Data Structures Used*********************/
union element
{ char sym;
int ival;
float fval;
};
struct info
{ element el;
char flag;
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
}expr;
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
/***************************Function declarations******************************/
char symb( char);
void display(Queue);
int insert();
void post_convert();
int evaluate();
void expression();
/****************************End of declarations******************************/
/*******************************Main Function**********************************/
void main()
{ clrscr();
expression();
getch();
}
/********************************End of Main***********************************/
/************************Other Function definitions****************************/
void expression()
{ int fail=insert();
if(fail==0)
post_convert();
fail=evaluate();
if(fail)cout<<"Error in eval ";
getch();
}
int insert()
{
int ctr=0,sign=1;
float factor;
char in[81];
info inf={ 0,0}; //INPUT is by default integer
cin.getline(in,81);
for(int i=0;in[i]!='\0';i++)
{ if(in[i]==' ')continue;
if(symb(in[i]))
{
if(in[i]=='-'&&(symb(in[i-1])||i==0)&&in[i-1]!=')')
//If operator is unary
{ sign=-1; //minus, change sign of
inf.flag=0; //factor, set flag as
continue; //integer, and continue
}
else if(symb(in[i])&&symb(in[i+1]))
if(in[i+1]!='('&&in[i+1]!='-'&&in[i+1]!='\0'&&in[i]!=')')
{ cout<<"Error!! too many operators!!!";
return -1;
}
else
sign=1;
if(in[i]=='(')
{ ctr++;
if(inf.flag!=2&&i!=0) //If there is no symbol
{ inf.el.sym='*'; //before '(', then
inf.flag=2; //multiply by default
expr.push(inf);
}
}
else if(in[i]==')')
ctr--;
inf.flag=2; //INPUT is a symbol(operator)
inf.el.sym=in[i];
expr.push(inf);
}
else if(isdigit(in[i]))
{ if(symb(in[i-1])||i==0)
{ inf.flag=0; //reset flag
inf.el.fval=0.0; //reset el
inf.el.ival=(int)(in[i]-'0')*sign;
}
else if(inf.flag)
{ factor/=10; //decrement the place value
//of last digit
inf.el.fval+=(in[i]-'0')*factor*sign;
}
else
inf.el.ival=10*inf.el.ival+(int)(in[i]-'0')*sign;
if(symb(in[i+1])||in[i+1]=='\0') …
i made a program to evaluate an expression, "expeval.cpp" [find attached].
i then tried to go further.....
i made the program to read characters from the keyboard and write it into a file["file.cpp",find attached]. if an expression is encountered, it is evaluated and the result is displayed after the line and also written into the file.
When the program encounters '==' the expression evaluation is initiated and when ';' is encountered, expression is terminated.
This, was working till i changed the input style. From gets to cin.get .
Then everything went wrong!
pls help me find wat went wrong!!!
:icon_confused:
Please..........i've got to submit the project within one week!!!:S
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<ctype.h>
/**********************Definitions of Data Structures Used*********************/
union element
{ char sym;
int ival;
float fval;
};
struct info
{ element el;
char flag;
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
}expr;
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
/***************************Function declarations******************************/
char symb( char);
void display(Queue);
int insert();
void post_convert();
int evaluate();
void expression();
/****************************End of declarations******************************/
/*******************************Main Function**********************************/
void main()
{ clrscr();
expression();
getch();
}
/********************************End of Main***********************************/
/************************Other Function definitions****************************/
void expression()
{ int fail=insert();
if(fail==0)
post_convert();
fail=evaluate();
if(fail)cout<<"Error in eval ";
getch();
}
int insert()
{
int ctr=0,sign=1;
float factor;
char in[81];
info inf={ 0,0}; //INPUT is by default integer
cin.getline(in,81);
for(int i=0;in[i]!='\0';i++)
{ if(in[i]==' ')continue;
if(symb(in[i]))
{
if(in[i]=='-'&&(symb(in[i-1])||i==0)&&in[i-1]!=')')
//If operator is unary
{ sign=-1; //minus, change sign of
inf.flag=0; //factor, set flag as
continue; //integer, and continue
}
else if(symb(in[i])&&symb(in[i+1]))
if(in[i+1]!='('&&in[i+1]!='-'&&in[i+1]!='\0'&&in[i]!=')')
{ cout<<"Error!! too many operators!!!";
return -1;
}
else
sign=1;
if(in[i]=='(')
{ ctr++;
if(inf.flag!=2&&i!=0) //If there is no symbol
{ inf.el.sym='*'; //before '(', then
inf.flag=2; //multiply by default
expr.push(inf);
}
}
else if(in[i]==')')
ctr--;
inf.flag=2; //INPUT is a symbol(operator)
inf.el.sym=in[i];
expr.push(inf);
}
else if(isdigit(in[i]))
{ if(symb(in[i-1])||i==0)
{ inf.flag=0; //reset flag
inf.el.fval=0.0; //reset el
inf.el.ival=(int)(in[i]-'0')*sign;
}
else if(inf.flag)
{ factor/=10; //decrement the place value
//of last digit
inf.el.fval+=(in[i]-'0')*factor*sign;
}
else
inf.el.ival=10*inf.el.ival+(int)(in[i]-'0')*sign;
if(symb(in[i+1])||in[i+1]=='\0')
expr.push(inf);
}
else if(in[i]=='.')
{ inf.el.fval=(float)inf.el.ival;
inf.flag=1; //INPUT is float type
factor=1; //Reset the place value
//of last digit added
if(symb(in[i+1])||in[i+1]=='\0')
expr.push(inf);
}
}
if(ctr>0)
while(ctr)
{ info inf={')',2};
expr.push(inf);
ctr--;
}
else if(ctr<0)
{ cout<<"Error!!! More right paranthesis!!!";
return -1;
}
return 0;
}
char symb(char c)
{ switch(c)
{ case '^':return 9;
case '/':return 8;
case '*':return 8;
case '+':return 7;
case '-':return 7;
case '(':return -1;
case ')':return 1;
default :return 0;
}
}
void display(Queue exp)
{ info inf={0,0};
while(inf.flag!=-5)
{ inf=exp.pop();
switch(inf.flag)
{ case 0 :cout<<"\nInteger : "<<inf.el.ival;break;
case 1 :cout<<"\nFloat : "<<inf.el.fval;break;
case 2 :cout<<"\nOperator: "<<inf.el.sym;break;
case -5:cout<<"\nEnd ofExpression";break;
default:cout<<"\nError in output";
}
}
}
void post_convert()
{ Queue temp;
Stack symbols;
info psym,pexp={'(',2};
symbols.push(pexp);
while(pexp.flag!=-5)
{ pexp=expr.pop();
if(pexp.flag==2)
{ psym=symbols.peek();
while((symb(psym.el.sym)>symb(pexp.el.sym))
&&pexp.el.sym!='(')
{ psym=symbols.pop(); //Push all operators of
temp.push(psym); //greater precedence
psym=symbols.peek(); //into expr
}
if(pexp.el.sym==')') //If the symbol is ')' , then
symbols.pop(); //remove '(' from the symbols
else //Else push the symbol into
symbols.push(pexp); //the symbols stack
}
else if(pexp.flag==-5)
{ psym=symbols.pop();
while(psym.el.sym!='(')
{ temp.push(psym);
psym=symbols.pop();
}
}
else
temp.push(pexp);
}
expr=temp;
}
int evaluate()
{ Stack eval;
info pexp,pnum,op1,op2,res;
int ctr=0;
pexp=expr.pop();
do
{ ctr++;
if(pexp.flag==1||pexp.flag==0) //if element is a number
eval.push(pexp); //push into stack
else if(pexp.flag==2)
{ op2=eval.pop();
op1=eval.pop();
if(op1.flag||op2.flag) //if op1 or op2 is float type
res.flag=1; //the result is float
else if(op1.flag==-5) //else if there is no element
cout<<"Too less operands"; //in stack, display error
else //else
res.flag=0; //the result is int type
switch(pexp.el.sym)
{ case '+' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '-' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '*' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '/' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
break;
default :cout<<"\nError!!in eval"<<pexp.el.sym;return-1;
}
eval.push(res);
}
pexp=expr.pop();
}while(pexp.flag!=-5);
res=eval.pop();
op1=eval.pop();
if(op1.flag!=-5)
return -1;
cout<<"\nOUTPUT : "<<(res.flag?res.el.fval:res.el.ival);
return 0;
}
/*******************************End of Definitions****************************/
/***********************Definition of Queue class functions*******************/
void Queue::push(info n)
{ if(front==NULL)
front=rear=new node;
else
{ rear->next=new node;
rear=rear->next;
}
if(rear==NULL)
cout<<"Error cannot insert in Q";
rear->inf=n;
}
info Queue::pop()
{ if(front==NULL)
{ info temp={0,-5};
return temp;
}
info temp=front->inf;
node *temptr=front;
if(front==rear) front=rear=NULL;
else
front=front->next;
delete temptr;
return temp;
}
/*******************************End of Definitions****************************/
/*********************Function Definitions of Stack Class**********************/
void Stack::push(info n)
{ node* temp=new node;
if(temp==NULL)
{ cout<<"Cannot insert into stack!!!";
return;
}
temp->inf=n;
temp->next=top;
top=temp;
}
info Stack::pop()
{ if(top==NULL)
{ info temp={0,-5};
return temp;
}
info n=top->inf;
node* temp=top;
top=top->next;
delete temp;
return n;
}
/********************************End of Definitions***************************/
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<ctype.h>
/**********************Definitions of Data Structures Used*********************/
union element
{ char sym;
int ival;
float fval;
};
struct info
{ element el;
char flag;
};
class Queue
{ struct node
{ info inf;
node *next;
}*front,*rear;
public:
Queue()
{front=rear=NULL;}
void push(info n);
info pop();
info peek()
{return front->inf;}
};
class Stack
{ struct node
{ info inf;
node *next;
}*top;
public:
Stack()
{top=NULL;}
void push(info);
info pop();
info peek()
{return top->inf;}
};
/******************************End of definitions******************************/
//Defining Global objects and variables
fstream temp;
Queue expr;
int exp_flag;
/***************************Function declarations******************************/
char symb( char);
void display(Queue);
int insert();
void post_convert();
int evaluate();
int expression();
/****************************End of declarations******************************/
/*******************************Main Function**********************************/
void main()
{ clrscr();
temp.open("temp.mth",ios::out|ios::in);
char ch;
cin.get(ch);
while(ch!=7)
{ exp_flag=0;
if(ch=='=')
{ cin.get(ch);
if(ch=='=')
exp_flag=expression();
else
temp.put('=');
if(exp_flag)
cout<<"Error : Expression syntax error!!";
}
else
temp.put(ch);
cin.get(ch);
}
getch();
}
/********************************End of Main***********************************/
/************************Other Function definitions****************************/
int expression() //converts infix expression to postfix and evaluates
{ exp_flag=0;
int fail=insert();
cout<<"return frm insert()";
if(fail)return -1;
post_convert();
cout<<"\nreturn from post_convert()";
fail=evaluate();
cout<<"\nreturn from evaluate()"<<fail;
if(fail)
{ char in[81];
if(exp_flag==1) //Remove input expression if
temp.getline(in,81,'\n'); //output failed
return -1;
}
return 0;
}
int insert() //insert into queue
{ int ctr=0,sign=1,MinusFlag=1;
float factor;
char in[81];
info inf={ 0,0}; //INPUT is by default integer
for(int i=0;i<81&&in[i-1]!=';';i++)
{ cin.get(in[i]);
if(isspace(in[i]))i--;
}
for(i=0;in[i]!=';';i++)
{
if(symb(in[i]))
{
if(in[i]=='-'&&MinusFlag)
//If operator is unary
{ sign=-1; //minus, change sign of
inf.flag=0; //factor, set flag as
continue; //integer, and continue
}
else if(symb(in[i])&&symb(in[i+1]))
if(in[i+1]!='('&&in[i+1]!='-'&&in[i]!=')')
{ cout<<"Error!! too many operators!!!";
return -1;
}
else
sign=1;
if(in[i]=='(')
{ ctr++;
if(inf.flag!=2&&i!=0) //If there is no symbol
{ inf.el.sym='*'; //before '(', then
inf.flag=2; //multiply by default
expr.push(inf);
}
}
else if(in[i]==')')
ctr--;
if(in[i]=='-') MinusFlag=1;
inf.flag=2; //INPUT is a symbol(operator)
inf.el.sym=in[i];
expr.push(inf);
}
else if(isdigit(in[i]))
{ if(symb(in[i-1])||i==0)
{ inf.flag=0; //reset flag
inf.el.fval=0.0; //reset el
inf.el.ival=(int)(in[i]-'0')*sign;
}
else if(inf.flag)
{ factor/=10; //decrement the place value
//of last digit
inf.el.fval+=(in[i]-'0')*factor*sign;
}
else
inf.el.ival=10*inf.el.ival+(int)(in[i]-'0')*sign;
if(symb(in[i+1])||in[i+1]==';')
expr.push(inf);
}
else if(in[i]=='.')
{ inf.el.fval=(float)inf.el.ival;
inf.flag=1; //INPUT is float type
factor=1; //Reset the place value
//of last digit added
if(symb(in[i+1])||in[i+1]==';')
expr.push(inf);
}
}
if(ctr>0)
while(ctr)
{ info inf={')',2};
expr.push(inf);
ctr--;
}
else if(ctr<0)
{ cout<<"Error!!! More right paranthesis!!!";
return -1;
}
temp.write(in,(i-1));
temp<<'\n';
exp_flag=1;
return 0;
}
char symb(char c)
{ switch(c)
{ case '^':return 9;
case '/':return 8;
case '*':return 8;
case '+':return 7;
case '-':return 7;
case '(':return -1;
case ')':return 1;
default :return 0;
}
}
void display(Queue exp)
{ info inf={0,0};
while(inf.flag!=-5)
{ inf=exp.pop();
switch(inf.flag)
{ case 0 :cout<<"\nInteger : "<<inf.el.ival;break;
case 1 :cout<<"\nFloat : "<<inf.el.fval;break;
case 2 :cout<<"\nOperator: "<<inf.el.sym;break;
case -5:cout<<"\nEnd ofExpression";break;
default:cout<<"\nError in output";
}
}
}
void post_convert()
{ Queue temp;
Stack symbols;
info psym,pexp={'(',2};
symbols.push(pexp);
while(pexp.flag!=-5)
{ pexp=expr.pop();
if(pexp.flag==2)
{ psym=symbols.peek();
while((symb(psym.el.sym)>symb(pexp.el.sym))
&&pexp.el.sym!='(')
{ psym=symbols.pop(); //Push all operators of
temp.push(psym); //greater precedence
psym=symbols.peek(); //into expr
}
if(pexp.el.sym==')') //If the symbol is ')' , then
symbols.pop(); //remove '(' from the symbols
else //Else push the symbol into
symbols.push(pexp); //the symbols stack
}
else if(pexp.flag==-5)
{ psym=symbols.pop();
while(psym.el.sym!='(')
{ temp.push(psym);
psym=symbols.pop();
}
}
else
temp.push(pexp);
}
expr=temp;
}
int evaluate()
{ Stack eval;
info pexp,pnum,op1,op2,res;
int ctr=0;
pexp=expr.pop();
do
{ ctr++;
if(pexp.flag==1||pexp.flag==0) //if element is a number
eval.push(pexp); //push into stack
else if(pexp.flag==2)
{ op2=eval.pop();
op1=eval.pop();
if(op1.flag||op2.flag) //if op1 or op2 is float type
res.flag=1; //the result is float
else if(op1.flag==-5) //else if there is no element
cout<<"Too less operands"; //in stack, display error
else //else
res.flag=0; //the result is int type
switch(pexp.el.sym)
{ case '+' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)+
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '-' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)-
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '*' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)*
(op2.flag?op2.el.fval:op2.el.ival);
break;
case '/' :if(res.flag)
res.el.fval=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
else
res.el.ival=
(op1.flag?op1.el.fval:op1.el.ival)/
(op2.flag?op2.el.fval:op2.el.ival);
break;
default :cout<<"\nError!!in eval"<<pexp.el.sym;return-1;
}
eval.push(res);
}
pexp=expr.pop();
}while(pexp.flag!=-5);
res=eval.pop();
op1=eval.pop();
if(op1.flag!=-5)
return -1;
cout<<"OUTPUT of expressions in the last line : "
<<(res.flag?res.el.fval:res.el.ival)<<'\n';
temp<<'$'<<'#';
temp.write((char*) &res,sizeof res);
return 0;
}
/*******************************End of Definitions****************************/
/***********************Definition of Queue class functions*******************/
void Queue::push(info n)
{ if(front==NULL)
front=rear=new node;
else
{ rear->next=new node;
rear=rear->next;
}
if(rear==NULL)
cout<<"Error cannot insert in Q";
rear->inf=n;
}
info Queue::pop()
{ if(front==NULL)
{ info temp={0,-5};
return temp;
}
info temp=front->inf;
node *temptr=front;
if(front==rear) front=rear=NULL;
else
front=front->next;
delete temptr;
return temp;
}
/*******************************End of Definitions****************************/
/*********************Function Definitions of Stack Class**********************/
void Stack::push(info n)
{ node* temp=new node;
if(temp==NULL)
{ cout<<"Cannot insert into stack!!!";
return;
}
temp->inf=n;
temp->next=top;
top=temp;
}
info Stack::pop()
{ if(top==NULL)
{ info temp={0,-5};
return temp;
}
info n=top->inf;
node* temp=top;
top=top->next;
delete temp;
return n;
}
/********************************End of Definitions***************************/
Newton-raphson iterative formula for f(x)=0; is
x2=x1-f(x1)/f'(x1);
u have to find the root of (x^3)-a=0;
so the formula is x2=x1-((x1^3)-a)/(3x1^2);
orx2=(2x1+a/x1^2)/3;
In other words u got ur formula wrong.
Now let us do the 100 prob with this formula-
assume x=1
after Pass 1 x= 34
Pass2 x=22.695501
Pass3 x=15.195048
Pass4 x=10.274402
Pass5 x=7.165367
Pass6 x=5.426147
Pass7 x=4.749559
Pass8 x=4.644025
Pass9 x=4.64159
Pass10 x=4.641589
Hope that clears ur prob.
Hi, I'm George from India. I'm doing my last year in school. I love programming. Here for some real programming experience. To learn from all u Big B's here.