Complex

Hello. I need to print out the total (summation of all complex numbers) I retrieved from the complex.txt files and I'm having problems...Can someone help please...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream> // Directive for iostrem library.
#include <fstream>

using namespace std; // namespace is a collection of identifiers in the standard library.

class Complex // Type Object
{                   
	double real;
	double img;
public:       // Constructors
	Complex(double a=0, double b=0); 
	void set_real(double a);
	void set_img(double b);
	double get_real();
	double get_img();
	void print();
	Complex plus(Complex c);
	Complex minus(Complex c);
	Complex mul(Complex c);
	Complex div(Complex c);
};  
Complex Complex::minus(Complex c) // Complex Operator
{
	Complex x;
	x.real = real - c.real;
	x.img = img - c.img;
	return x;
}
Complex Complex::mul(Complex c) // Complex Operator
{
	Complex x;
	x.real = real * c.real -img * c.img;
	x.img = img * c.real + real * c.img;
	return x;
}
Complex Complex::div(Complex c) // Complex Operator
{
	Complex x;
	double temp = c.real * c.real + c.img * c.img;
	x.real = (real * c.real + img * c.img) / temp;
	x.img = (img * c.real - real * c.img) / temp;
	return x;
}
#include "Complex.h"

 int main()
{
 Complex total;
 Complex *ptr;
 double a, b;
 int num, i;
  ifstream fin; //creates ifstream object called fin

     fin.open("complex.txt"); //opens "filename.txt"

	 cout << "This is what is inside of complex.txt: \n ";

	 char ch;

     while(fin.get(ch)) //reads characters from the file

            cout << ch; //prints characters to the screen
	fin.close(); //closes the file "complex.txt"
	cin >> num; // !!!This is where the program stop running!!!
 ptr = new Complex[num];
 for ( i = 0; i < num; i++)
 {
	 cin>>a>>b;
	 ptr[i].set_real (a);
	 ptr[i].set_img (b);
	 total = total = total.plus (ptr[i]);
 }
 cout<<"The total is ";
 total.print();
 cout<<endl;
 return 0;
 }
        
line 64 is asking the user to enter value for num instead of getting num from file. try this:

I assumed you wanted to read the values for a and b from the file. on line 68 you are again asking the user to input these values. Below fixes that as well/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
num=0;
while(fin.get(ch))
     ++num;
fin.clear();
fin.seekg(0);

ptr=new Complex[num];
for(i=0;i<count/2;++i)
{
     fin>>a>>b;
     ptr[i].set_real (a);
     ptr[i].set_img (b);
     total = total = total.plus (ptr[i]);
 }

THANKS SO MUCH FOR THE HELP...IT WORKED PERFECTLY...GLAD TO HAVE MET YOU...
Topic archived. No new replies allowed.