Quote:Original post by Buckeye
Off the top of my head:
std::string line;std::getline( fstream, line, '\n');int a, b, c, f;float d, e;sscanf(line.c_str(),"%d, %d, %d, %f, %f, %d",&a, &b, &c, &d, &e, &f);
No. sscanf in C++ is considered harmful, is less flexible, is slow, and is unreadable. It requires an uneccesary copy from getline. This is not "using fstream well"
Quote:Original post by KulSeran
Doing that all in C++ would involve writing it like:
*** Source Snippet Removed ***
edit: whoops.... i read that too fast, and didnt see you had different types in there. Fixed my example.
edit edit: *whew* fixed
No. This code is extremely complex, uses templates, and also uses the unnessecary copy from getline. Furthermore, the final api it exposes calls sevral functions and is very unlike C++ built-in text-file serialization api. This is also not "using fstream well"
A good use of fstream for object serialization would utilize a single operator overload on the istream& to serialize the object using standard >> operators from ANY stream type. Furthermore it would avoid un-needed copy constructors and function overhead. Here is my version.
#include <iostream>#include <fstream>#include <string>struct Object{bool a;int b,c,f;float d,e;Object( bool A, int B, int C, float D, float E, int F) : a(A), b(B), c(C), d(D), e(E), f(F) {}Object(){};};std::istream& operator>>(std::istream& in,Object& obj){ char comma; //storage for useless comma ops; in >> obj.a >> comma >> obj.b >> comma >> obj.c >> comma >> obj.d >> comma >> obj.e >> comma >> obj.f; return in; //for chaining inputs}std::ostream& operator<<(std::ostream& out,const Object& obj){ out << (int)obj.a << ',' << obj.b << ',' << obj.c << ',' << obj.d << ',' << obj.e << ',' << obj.f; return out; //for chaining outputs;}int main(int argc, char **argv){ std::ifstream ifile( "test.txt" ); int value = 0; std::string line; while(ifile) { Object o; ifile >> o; //getline(ifile,line); //optional: skip to end of line after parsing object by reading empty chars into line string. This should prevent extra reading of the last line, but it might not std::cout << o << std::endl; } return 0;}