简体   繁体   中英

c++ write all values of an array into txt file

I've defined var like

typedef struct{
    float x;
    float y;
    float z;
} 3DPOINT;

then, in my code, I set an array that contains 3DPOINT

3DPOINT myArray[1280];

I properly fill this array and now I need to write each position into txt file.

std::ofstream fs("c:\\testvalues.txt");

for (int i=0;i<1280;i++)
    {
        //here I must get array position data and convert it to string
        fs<<myArrayPositionToString<<"\x0D\x0A";
    }

    fs.close();

This looks like a homework problem, but the << operator of fstream does the conversion for you.

fs<<myArray[i].x<<"\t"<<myArray[i].y<<"\t"<<myArray[i].z<<endl;

The "\\t"-s are tabs, you can also use simple spaces if you'd like.

If you want to use operator<< on your struct , you will have to define an operator<< function for your structure.

Search StackOverflow for "overloading insertion operator ostream".

Also search the web for "C++ FAQ operator overloading <<".

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