vidit_X 29 Junior Poster

Please correct the code tags.

>> operator reads until the first whitespace character. So when you are reading the file which has "burcin eric 783389" with the following code

f>>name1>>numb1;

name1 gets burcin and numb1 gets erec.

vidit_X 29 Junior Poster

What's the exact error?

vidit_X 29 Junior Poster

After generating a random number inside the second for loop, you are comparing it with the current index only.

Instead you should check whether the number is in that row or column, if its not, accept it else generate a new one and repeat the above.

vidit_X 29 Junior Poster

Hint : You are adding elements to tree's root only.

And what's the purpose of line 97.

array[index];
vidit_X 29 Junior Poster

But the closing brace for do loop is at line 51 ... the while should be after it.

vidit_X 29 Junior Poster

Where's the while for do loop?

vidit_X 29 Junior Poster

Try it dude .. will give you a hint.
Why do you need to have parameters in get function? The variables with values already exists, just return them. If you still don't get it, feel free to ask.

vidit_X 29 Junior Poster

How about setw()?

vidit_X 29 Junior Poster

In reduce function, you are equating x and y to local uninitialized variables a and b which should give errors.

Set function looks ok, but in get you are returning parameter values instead of actual numerator and denominator values.

I have not checked the logic of your program.

vidit_X 29 Junior Poster

Declare find() before main() and it should work.

bool find(int&,int)
vidit_X 29 Junior Poster

cout<<"String";

The "String" should start and end on same line in the editor or you can extend it like ..

cout<<"Str"
<<"ing";

vidit_X 29 Junior Poster

Hey Narue, if we just change the paramenter passing to "pass by reference", the function would accept a File pointer?

vidit_X 29 Junior Poster

I tried compiling the header "Globals.h" and the first cpp defining GlobalVars().
It didn't give any error.

vidit_X 29 Junior Poster

In simple interest, you need to add fixed interest to the sum1 every time in the loop.

sum1=deposit1*interest1/100 + sum1;

In compound interest, you need to calculate interest every time in the loop and add it to the sum.

sum=sum*interest2/100 + sum;

Don't just increment it, you are just adding 1 to the sum1 and sum every time in the loop.

vidit_X 29 Junior Poster

First thing, don't use system("pause").

Why sum1==sum, the question says when the investment of Celio exceeds Daphne's.
Also in loop, you are just incrementing sum1 and sum... do you think that's correct?

vidit_X 29 Junior Poster

I don't think it'll work because ifstream won't work with File pointer i.e ifstream parameter won't accept a File Pointer.

vidit_X 29 Junior Poster

Don't use System("pause"), instead as LordNemrod suggested use cin.get().

vidit_X 29 Junior Poster

Is it that you want the menu to be displayed according to the Account ID?
Can you please detail a little more about your problem.

vidit_X 29 Junior Poster

k, thanks for that AD. I didn't knew of this optimized version.

But NervousWreck code also looks fine to me .. don't know what's wrong in it logically.

vidit_X 29 Junior Poster

@Ancient Dragon - His Bubble sort looping looks fine.

vidit_X 29 Junior Poster

Try using the complete path withing double quotes ...

vidit_X 29 Junior Poster

You can't get something from an output stream ...

Do you want to read a single character at a time from a file, crypt it and then put it back on a new file?

vidit_X 29 Junior Poster

@mitrmkar - Verifying the move is a good option, but its like an addon to the main program, so I'll do it later. Thanks for the idea. Any other suggestion?

@firstPerson & WaltP - I know that a file's automatically closed by the program but remove() doesn't works if any references to file exists or if the file is currently open. So as to use remove, I closed the files.

I thought of using functions for read and write, they surely will make the program more readable and modular but they increased the code which I felt like is redundant.

About throwing exceptions, I was doing so because it was asked in the problem. I'm trying to make exception throwing efficient and proper.

And should we clear dynamic memory allocated or leave it to the compiler?

Please correct me if I'm wrong anywhere...

vidit_X 29 Junior Poster

While I don't know if it buys the OP anything it's as legal as saying a<10, it's still a condition that returns true or false.

But dword[a] > 0 will compare the ASCII value of the character at 'a' index of dword, which will always be greater than 0, right? Also, its error acc. to my compiler.

@kangarooblood-
Since you are not using 'i' anywhere in the loop why declare it?
If you want to loop till the end of string, the for loop can be like

for(;dword[a]!='\0';++a)

or as jonsca said.

vidit_X 29 Junior Poster

In for loop, you used condition "dword[a] > 0" ? What you meant by that?

You using an old compiler? inlcuding <iostream.h>
You should not use goto, it creates bad code instead use do while.

vidit_X 29 Junior Poster

First of all, you cant have array of strings in char array. You need to have a 2D char array or a 1D string array like this ..

char wordToBeGuessed[][10]={cat,dog,......};

where 10 is the maximum size of any word in the list.

Now, before asking user to input a word, choose a random word out of the list. You can use rand() for that ..

int i=rand() % X;

where X is the number of words in the list.

And you'll need to input a single character and then check whether that letter is in the selected word until either the number of tries end or word is guessed correctly.

vidit_X 29 Junior Poster

You coded something?

Try it yourself first, if you have any problem then we'll help.

vidit_X 29 Junior Poster

I didn't got you completely. Why to use Find and replace?

For Encryption :
Open the file, read the lines in a string, call encrypt and then store back.
For Decryption :
Open the file, read the lines in a string, call decrypt and then store back.

Is that what you want?

vidit_X 29 Junior Poster

@WaltP - Any corrections for the code?

@AncientDragon - Can you please change the "Practise" to "Practice" in title?

vidit_X 29 Junior Poster
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int mv(const string&,const string&);

int main()
{
	string source, dest;

	cout<<"Enter FilePath, source -";
	cin>>source;
	cout<<"Enter FilePath, Destination -";
	cin>>dest;
	
	try{
		mv( source, dest );
	}catch( char er[] ) {
		cout<<er;
		return -1;
	}

	cin.get();
	return 0;
}

int mv(const string &a,const string &b)
{
	fstream				file1, file2;
	fstream::pos_type	        size;
	char                            *data;

	file1.open( a.c_str(), ios::in | ios::binary | ios::ate );
	file2.open( b.c_str(), ios::out | ios::binary );

	if( !file1.is_open() ) {
		throw "Error Opening File";
		return -1;
	}

	if( !file2.is_open() ) {
		throw "Error Writing File";
		return -1;
	}

	size=file1.tellg();                    //Get the size of file1
	data=new char[size];
	file1.seekg( ios::beg );             //Set the get pointer at ios::beg
	file1.read( data, size );              //read the file1
	file2.write( data, size );             //write the file2
	file1.close();                         //close file1
	file2.close();                         //close file2
	delete[] data;                         //free memory

	if( remove( a.c_str() ) ) {
		throw "Error Moving File";
		return -1;
	}

	return 0;
}

Hows the formatting now?
Any other suggestions or corrections are welcome.

Ancient Dragon commented: good formatting effort :) +26
vidit_X 29 Junior Poster

I try to format as well as I can, but I never get it the right way.
Can I get a model code, so that I can learn the proper way of formatting?

Thanks WaltP. Any other suggestions or corrections are welcome.

vidit_X 29 Junior Poster

Anyone..

vidit_X 29 Junior Poster

Here's a little modified code using std::string.

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int mvfile(const string&,const string&);

int main(){
 string source,dest;
 cout<<"Enter FilePath, source -";
 cin>>source;
 cout<<"Enter FilePath, Destination -";
 cin>>dest;
 try{
         mvfile(source,dest);
 }catch(char er[]){
	 cout<<er;
	 return -1;
 }
 return 0;
}

int mvfile(const string &src,const string &dest){
 fstream file1,file2;
 fstream::pos_type size;
 char *data;
 file1.open(src.c_str(),ios::in|ios::binary|ios::ate);
 file2.open(dest.c_str(),ios::out|ios::binary);
 if(!file1.is_open()){
	 throw "Error Opening File";
	 return -1;
 }
 if(!file2.is_open()){
	 throw "Error Writing File";
	 return -1;
 }
 size=file1.tellg();
 data=new char[size];
 file1.seekg(ios::beg);
 file1.read(data,size);
 file2.write(data,size);
 file1.close();
 file2.close();
 delete[] data;
 if(remove(src.c_str())){
   throw "Error Moving File";
   return -1;
 }
 return 0;
}

Hows this one? Any suggestions or comments are welcome.

vidit_X 29 Junior Poster
s=temp

s a char array & temp a strng object.

return s

What's the return type of operator +=? Is is char*?

vidit_X 29 Junior Poster

I accept this code is not good though its working, catching exceptions all as asked in question.

Members here are experts, so helping and friendly. I'm sure I'll improve my code as well as coding here.

P.S: How to edit the thread title? Don't know how I typed it wrong :(

vidit_X 29 Junior Poster

Question by ~s.o.s~
Write a program which will perform the job of moving the file from one location to another. The source and destination path will be entered by the user. Perform the required error checking and handle the exceptions accordingly. (Intermediate)

#include<fstream>
#include<iostream>
#include<cstdio>
using namespace std;
int main(){ 
 fstream a,b;
 char f1[100],f2[100],x[100];
 cout<<"Enter file1 path";
 cin.getline(f1,100);
 cout<<"Enter file2 path";
 cin.getline(f2,100);
 try {
	 a.open(f1,ios::in|ios::binary);
	 if(!a)
		 throw 1;
	 try {
		 b.open(f2,ios::out|ios::binary);
		 if(!b)
			 throw 1;
		 while(!a.eof()){
			 a.getline(x,100);
                         b<<x<<"\n";
		 }
	 }catch(int i) {
		 cout<<"Error Writing file";
		 cin.get();
		 cin.get();
		 return -1;
	 }
 }catch(int i) {
	 cout<<"Error opening File";
	 cin.get();
	 cin.get();
	 return -1;
 }
 a.close();
 b.close();
 try{
	 if(remove(f1))
		 throw 1;
	 cout<<"File Moved";
 }catch(int i) {
	 cout<<"Error moving file";
	 cin.get();
	 cin.get();
	 return -1;
 }
 cin.get();
 cin.get();
 return 0;
}

What is the complexity of the above code?
Any corrections, comments or suggestions are welcomed :)

vidit_X 29 Junior Poster

Thanks to all, for their valuable suggestions and comments :)

Thread Solved.

vidit_X 29 Junior Poster

Thanks dusktreader for answering :)

notice that I overloaded the () operator to allow access to an item by (row, col), so Mat( i, j ) will return the item at the ith row, jth column. You can easily expose 2d functionality ( or higher D if you are careful and clever ) to a user while preserving the underlying 1D structure.

I too overloaded (), but still if we choose two dimensional array, then it'll have similar memory allocation as user might expect for a matrix. Anyway, I think we both are right and it can be implemented either way.

Actually, I looked at your code while reading the line "it keeps the code from executing a switch on every single iteration of the loop" and therefore got confused.

My conclusion: for native types, passing by value is fine, but for containers, classes, and structs use const references.

Nice explanation. Got your point.

Line 34 (and others): Inside of the scope of the Matrix class, you have access to the mat array member. So, you should use direct access instead of accessor functions within this scope. So use mat[j] = other.mat[j]. This is also more readable, and it is more obvious what is going on.

Mat[][] is a private member of class Matrix object other, can it be directly accessed? I don't think so.

Line 45 (and others): Move this conditional above the switch. There is no use repeating the same code in …

vidit_X 29 Junior Poster

Here's the revamped code ...

#include<iostream>
#include<iomanip>

using namespace std;

template <class X=int> class Matrix 
{
 private:
 static const int ADD='+';
 static const int SUB='-';
 static const int MLT='*';
 int row,col;
 X **mat;

 int init(const int&x,const int&y) {
  row=x;
  col=y;
  mat=new X*[row];
  for(int i=0;i<row;i++)
	  mat[i]=new X[col];
  return 0;  
 }

 int initv(const X& init) {
  for(int i=0;i<row;i++)
   for(int j=0;j<col;j++)
    mat[i][j]=init;
  return 0;
 }

 int initv(const Matrix& init) {
  for(int i=0;i<row;i++)
   for(int j=0;j<col;j++)
    mat[i][j]=init(i,j);
  return 0;
 }

 Matrix _arthimetichelper(const Matrix &other,const int& op)const {
  if(mat==NULL||other.mat==NULL)
   return Matrix();
  else
  switch(op)
  {
   case ADD:
    if(row!=other.returnrow()||col!=other.returncol())
     return Matrix();
    else
    {
     Matrix r(row,col);
     for(int i=0;i<row;i++)  
	  for(int j=0;j<col;j++)
	  r(i,j)=mat[i][j]+other(i,j);
	 return r;
    }
    break;
   case SUB:
    if(row!=other.returnrow()||col!=other.returncol())
     return Matrix();
    else
    {
     Matrix r(row,col);
     for(int i=0;i<row;i++)  
	  for(int j=0;j<col;j++)
	   r(i,j)=mat[i][j]-other(i,j);
	 return r;  
    }
    break;
   case MLT:
    if(col!=other.returnrow())
     return Matrix();
    else
    {
     Matrix r(row,other.returncol());
     for(int i=0;i<row;i++)  
	  for(int j=0;j<other.returncol();j++)
	   for(int k=0;k<col;k++)
	    r(i,j)+=mat[i][k]*other(k,j);
	 return r;  
    }
   break;
  };
 }
  
 public:
 Matrix() {
  mat=NULL;
 }
 
 Matrix(const int& x, const int& y) {
  init(x,y);
  initv(0);
 }
 
 Matrix(const int&x, const int& y, const X& init) {
  init(x,y);
  initv(init);
 }
 
 Matrix(const Matrix &other) {
  init(other.returnrow(),other.returncol());
  initv(other);
 }
 
 ~Matrix() {
  for(int i=0;i<row;i++)
    delete[] mat[i];
  delete[] mat;
 }
  
 int returnrow() const {
  return row;
 }
 
 int returncol() const { 
  return col;
 }
 
 X& operator()(const int& x,const int& y) const {
  if(x>=row||x<0||y>=col||y<0)
   cout<<"Error! Enter correct dimensions";
  else
   return mat[x][y];
 }
 
 friend ostream& operator<<(ostream& stream,const Matrix& y) {
  if(!y.mat) {
   stream<<"Empty Matrix\n";
   return stream;
  }
  else {
  for(int i=0;i<y.row;i++) {
    stream<<"\n";
    for(int j=0;j<y.col;j++)
	stream<<setw(3)<<y(i,j)<<" ";
   }
  return stream;
  }
 } …
vidit_X 29 Junior Poster

Put a check on the input numbers before operating on them.

vidit_X 29 Junior Poster

@firstPerson - Thanks again for answering my queries :)
@dusktreader - Thanks for the code, I'll take hints from that. I thought of using single dimensional array for representing the matrix but then change to two dimensional to support user's view of the matrix. I might implement additional functionalities once I recode all the above functionalities properly. Also, I didn't got what you meant by this "but it keeps the code from executing a switch on every single iteration of the loop" :-/

I have almost completed the recoded code. But in the meanwhile, have some more questions which I got while coding acc. to the comments.
1. Starting the name of functions with underscore is another convention like _arithmetichelper? I have seen many.
2. We group the operators(+,-,*) functionality together in a different functions bcoz they are almost simliar, right?
Also for the code in constructor, we group them in a function bcoz of similar functionality, right?
3. Why to use static const int variables like ADD, SUB etc to be passed as parameters to _arithmetichelper()? I mean cant we use any other parameter like const ints and pass 0 or 1 as argument?
4. What is the benefit of making _arthimetichelper() as private?

Any more comments or corrections are welcomed.

vidit_X 29 Junior Poster

@firstPerson - that's a whole lot of corrections. Thanks for all that :)
I'll revamp all my code and post it here in my next post.

Meanwhile, I have some doubts regarding those comments and corrections.
1. You emphasized on using const wherever I can, I'll but may I know why it is good?
2. If I use parameterless constructor like as u said Matrix(), how'll I initialize dimensions?
3. Can you give me a little more hint on that private function, to be used in constructor?
4. const-corrected means using const parameteres in functions?
5. Why pass matrix in operator function as reference when I wont be modifying them?

Any other comments or corrections are welcomed.

vidit_X 29 Junior Poster

@niek_e - Thanks for your suggestions.
1. I agree, my operator class should not have cout. As an operator never outputs, it just performs operation. Got your point.

2. Oops, I missed it. It surely needs freeing, here's the destructor code -

~matrix()
{
 for(int i=0;i<dim2;i++)
  delete[] mat[i];
 delete[] mat;
}

3. I intentionally didn't used switch bcoz there were only 3 cases, I thought if else ladder would be better.

vidit_X 29 Junior Poster

Thanks WaltP for your suggestion.
I'll take care of all that from next time. Any other suggestion?

vidit_X 29 Junior Poster

Practise problem by ~s.o.s~
Q. Write a program which performs addition, subtraction, multiplication of matrices. The dimensions of both the matrices would be specified by the user (dynamic memory allocation required). Use of structure or a class to define the matrix would be a good idea. (Expert)

#include<iostream>
using namespace std;
class matrix
{
 int dim1,dim2;
 int **mat;
 public:
 matrix(int x=2,int y=2)
 {
  dim1=x;
  dim2=y;
  mat=new int*[dim1];
  for(int i=0;i<dim1;i++)
	  mat[i]=new int[dim2];
  for(int i=0;i<dim1;i++)
   for(int j=0;j<dim2;j++)
    mat[i][j]=0;
 }
 int returndim1()
 {
  return dim1;
 }
 int returndim2()
 { 
  return dim2;
 }
 void input()
 {
  cout<<"Enter the elements of matrix - ";
  for(int i=0;i<dim1;i++)
   for(int j=0;j<dim2;j++)
    cin>>mat[i][j];
 }
 void out()
 {
  for(int i=0;i<dim1;i++)
   {
    cout<<"\n";
    for(int j=0;j<dim2;j++)
	cout<<mat[i][j]<<" ";
   }
 } 
 matrix operator+(matrix x)
 {
  matrix c(dim1,dim2);
  if(dim1==x.returndim1() && dim2==x.returndim2())
   {    
    for(int i=0;i<dim1;i++)
      for(int j=0;j<dim2;j++)
	   c.mat[i][j]=this->mat[i][j]+x.mat[i][j];
	return c;
   }
  else
  {
   cout<<"Matrix cant be added";  
   return c;  
  }
 }
 matrix operator-(matrix x)
 {
  matrix c(dim1,dim2);
  if(dim1==x.returndim1() && dim2==x.returndim2())
   { 
    for(int i=0;i<dim1;i++)
      for(int j=0;j<dim2;j++)
	   c.mat[i][j]=this->mat[i][j]-x.mat[i][j];
	return c;
   }
  else
  {
   cout<<"Matrix cant be subtracted";  
   return c;  
  }
 }
 matrix operator*(matrix x)
 {
  matrix c(dim1,x.returndim2());
  if(dim2==x.returndim1())
   { 
    for(int i=0;i<dim1;i++)
      for(int j=0;j<x.returndim2();j++)
	     for(int k=0;k<dim2;k++)
	       c.mat[i][j]+=this->mat[i][k]*x.mat[k][j];
	return c;
   }
  else
  {
   cout<<"Matrix cant be multiplied";  
   return c;  
  }
 }
};
int main()
{
 int x,y;
 char ch;
 do{
 cout<<"Enter the dimension of matrix1 -";
 cin>>x>>y;
 matrix a(x,y);
 a.input();
 cout<<"\nEnter the dimension of matrix2 -";
 cin>>x>>y;
 matrix b(x,y);
 b.input();
 cout<<"\n1.Add\n2.Sub\n3.Multiply\n";
 cin>>x;
 if(x==1)
  (a+b).out();
 else if(x==2)
  (a-b).out();
 else if(x==3)
  (a*b).out();
 else
  cout<<"Wrong choice";
 cout<<"\nContinue(y/n)";
 cin>>ch;
 }while(ch=='y'||ch=='Y');
 cin.get(); …
vidit_X 29 Junior Poster

Thanks ohnomis for the prefix version "++points" . ;)
I think you should mark the thread as solved.

vidit_X 29 Junior Poster

Which compiler are you using? Strange error :O

vidit_X 29 Junior Poster

Do not initialize steps with command[++cmd], this will surely increment cmd before it even enters the switch statement. Just initialize the steps variable with any legal value. It will be better if you initialize steps before the loop as I said in previous post.

ohnomis commented: solver of declaring variables inside switch cases +1
vidit_X 29 Junior Poster

For prime function, have a look at this thread -
http://www.daniweb.com/forums/thread143933.html .
And for random function, have a look at this thread -
http://www.daniweb.com/forums/thread1769.html

vidit_X 29 Junior Poster

I think you can declare and intilialize steps after the function "processTurtleMoves" declaration.

void TurtleGraphics::processTurtleMoves( const int commands[] )
{
  int steps=0;
  .... .. .. 
  .... .. ..

}

This should solve the problem. And as WaltP said, use a prefix form rather than a postfix one.