Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read a comlex matrix from a file

Status
Not open for further replies.

tgel76

Programmer
Jul 2, 2001
17
GB
how can i read complex numbers from the file:

[
3.2+4.1i 5.3-6.4i;
4.3-9.1i 5.3+5.4i
]
the file has exactly this format and I have problems with the characters... the only way i could think is to read it as char and write two other files with the real and imag part without [,],i,; and the read that files and combine them... any other idea?
 
Hi tgel76
The following program worked fine. Although it may not be the best way but i think it's better than your idea of 2 files, etc...
Ofcourse u will have to modify it according to your requirements.
Code:
#include<stdio.h>
//#include<iostream.h>

main()
{
   clrscr();
   FILE *fp;

   fp = fopen(&quot;chk.txt&quot;, &quot;r&quot;);

   char c=0, sign;
   float real, imgn;

   c = fgetc(fp); // reads [
   while(c != ']')
   {
      while(c != ';' && c!= ']')
      {
         c = fgetc(fp);
         if(c != ';') ungetc((int)c, fp);
         if(c == ']') continue;
         fscanf(fp, &quot;%f %c %f %c&quot;,&real, &sign, &imgn, &c);
         if(sign == '-') imgn = imgn*(-1);
	 // your code ...
         // cout<<&quot;REAL &quot;<<real<<&quot; IMGN &quot;<<imgn<<&quot; C &quot;<<c<<endl;
	 // your code ...
         c = fgetc(fp);
      }//one row read
      c = fgetc(fp);
   }//the whole matrix read

return 0;
}
Hope this helps. I'm sure there are better ways. I would like to know too.
And yes using structure will help no doubt. But i guess the question was how to read the data into the variables whether using stucture or not.

Ankan :)
 
oops! :-( i forgot to delete the sixth line above (clrscr();). Please just ignore it.

Ankan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top