简体   繁体   中英

How to read an array of complex numbers from a text file in C++

As a learner in c++, I decided to play with complex numbers, using the standard library. Now I need to read and write an array of complex from/to text files. This works simply for writing, without supplemental tricks :

void dump(const char *filename){
  ofstream result;
  result.open (filename);
  for(int k=0;k<15;k++){
    result<< outputs[k] <<endl;
  }
  result.close();
}

The data are parenthesized and written line by line looking like : (real,im)...

Now, I guess reading (and loading an array of complex) should be as trivial as reading. However, despite my research, I have not found the right way to do that.

My first attempt was naive :

void readfile(const char *filename){
  string line;
  ifstream myfile (filename);
  if (myfile.is_open())
  {
    int k=0;
    while ( getline (myfile,line) ){
      k++;
      cout << line << endl;
      inputs[k]= (complex<float>) line; //naive !
    }
    myfile.close();
  }
  else cout << "Unable to open file"; 
}

Is there a way to do that simply (without a string parser ) ?

C++ version:

std::complex<int> c;
std::ifstream fin("filename");
fin>>c;

C version:

int a,b;
FILE *fin=fopen("filename","r");
fscanf(fin,"(%d,%d)\n",&a,&b);

C++ read multiple lines with multiple complex values on each line

#include <stdio.h>
#include <fstream>
#include <complex>
 #include <iostream>
 #include <sstream>
int main ()
{
    std::complex<int> c;
    std::ifstream fin("test.in");
    std::string line;
    std::vector<std::complex<int> > vec;
    vec.reserve(10000000);
    while(std::getline(fin,line))
    {
        std::stringstream stream(line);
        while(stream>>c)
        {
           vec.push_back(c);
        }
    }

    return 0;
}

Assuming you have an operator<< for your_complex_type (as has been mentioned, std::complex provides one), you can use an istream_iterator :

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "numbers.txt" );
    std::vector<your_complex_type> buffer{
            std::istream_iterator<your_complex_type>(input), 
            std::istream_iterator<your_complex_type>() };
}

This will read all numbers in the file and store them in an std::vector<your_complex_type> .

Edit about your comment

If you know the number of elements you will read up-front, you can optimize this as follows:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "numbers.txt" );
    std::vector<your_complex_type> buffer;
    buffer.reserve(expected_number_of_entries);

    std::copy(std::istream_iterator<your_complex_type>(input), 
              std::istream_iterator<your_complex_type>(),
              std::back_inserter(buffer));
}

std::vector::reserve will make the vector reserve enough memory to store the specified number of elements. This will remove unnecessary reallocations.

You can also use similar code to write your numbers to a file:

std::vector<your_complex_type> numbers; // assume this is filled
std::ofstream output{ "numbers.txt" };

std::copy(std::begin(numbers), std::end(numbers),
          std::ostream_iterator<your_complex_type>(output, '\n') );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM