pa***********@jhuapl.edu wrote:
This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iterator>
struct Test {
int i, j, k, l;
};
>
int main(int argc, char* argc){struct Test {
int i, j, k, l;
};
struct Test{
int i;
int j;
intk;
int l;
}
Types need a semicolon and are not placed in main()
>
Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;
Either an aggregate list or Test ctor would be handy.
Test test = {99, 777, 12345, 876};
>
fstream fout;
fout.open("test.txt", ios::out);
if(!fout || !fout.is_open() )
{
std::cout << "error while opening file for output.\n";
return -1;
}
>
for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();
If you wrote a global operator<< to stream Test data you'ld benefit
since operators can be reused for both writing to file and writing to
std::cout.
for (int i = 0; i < 10; ++i)
{
ofs << test; // depends on global op<<
}
>
fstream fin;
fin.open(test.txt", ios::in);
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
Test t2;
Don't use char, use std::string instead.
// input file stream
std::ifstream ifs;
ifs.open("test.txt"); // its set to std::ios::in already
if(!ifs || !ifs.is_open() )
{
std::cout << "error while opening file for input.\n";
return -1;
}
// load a vector with Test data
std::vector< Test vtest; // container
std::string buffer; // buffers each line
std::istringstream iss; // used to dissect data from buffer
while(std::getline(ifs, buffer, '\n'))
{
Test temp;
iss.str(buffer);
iss >temp.i >temp.j >temp.k >temp.l;
iss.clear();
vtest.push_back(temp); // push temp onto container
}
if(!ifs.eof()) // if std::getline did *not* fail because of eof...
{
std::cout << "error while reading file.\n";
std::cout << "end of file not found.\n";
return -1;
}
// print vector using copy algorithm
std::copy( vtest.begin(),
vtest.end(),
std::ostream_iterator<Test >( std::cout ));
return 0;
}
I leave the global operator<< to you as an exercise.
Have fun.