Marcus
Marcus

Reputation: 99

How to write the content of an array into a text file?

How to write the content of an array to a text file? Is it possible?

Below is my code:

x=0;
y=0;
//copy to real array
if(nRow == 0){
    for(i=nTCol; i>=0 ; i--){
        nPanelMap[nRow][x] = nTempMap[i];
        x++;
    }

}
if(nRow == 1){
    for (i=nTCol; i>=0 ; i--){
        nPanelMap[nRow][y] = nTempMap[i];
        y++;
    }
}
k=0;

for (i=nTCol; i>=0 ; i--){
    array [k] = nPanelMap[nRow][x];
    k++;
    array [k] = nPanelMap[nRow][y];
    k++;

}
j=0;
for (i=nTCol; i>=0 ; i--){

    nPanelMap[nRow][j] = array [k];
    j++;
}
nRow++;

I would like to print out arrays x, y, k, and j and write them into a text file. The purpose of doing this is to ensure that the data passing is correct.

Upvotes: 9

Views: 92688

Answers (3)

i'm PosSible
i'm PosSible

Reputation: 1393

Yes, you can write into a text file.

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  const int size = 5;
  double x[] = {1,2,3,4,5}; 

  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    for(int count = 0; count < size; count ++){
        myfile << x[count] << " " ;
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

More reference: http://www.cplusplus.com/doc/tutorial/files/

To write array data use this.

for(int count = 0; count < size; count ++){
            out_myfile << x[count] << " " ;
}

Upvotes: 13

Benilda Key
Benilda Key

Reputation: 3092

My suggestion is that you use the JSON (JavaScript Object Notation) format if you want the resulting file to be human readable. JSON is documented at http://json.org/. The ThorsSerializer found at https://github.com/Loki-Astari/ThorsSerializer is a C++ Serialization library for JSON. Serialization, as defined at http://en.wikipedia.org/wiki/Serialization, "is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment." If ThorsSerializer does not work for you, I suggest that you do a Google search for "C++ JSON Serialization library."

Another option I found when doing this Google search is "cereal - A C++11 library for serialization" found at http://uscilab.github.io/cereal/.

Upvotes: 2

Praful Surve
Praful Surve

Reputation: 788

Use fstream class for operations like file write, read, append, seek, etc..

Upvotes: 1

Related Questions