I was trying to write X objects in a file, to read it later, but I don't understand much about I/O in c++. X would be a class with a string and a number, just as an example. (I used a string, but it is not supposed to me just a letter)
#include <iostream>
#include <string>
#include <sstream>
class X {
int _number;
std::string _letter;
public:
X() { _number = 0; _letter = "anonimo"; }
X(int number, std::string letter) { _number = number; _letter = letter; }
int getnumber() { return _number; }
std::string getletter() { return _letter; }
void setNumber(int number) { _number = number; }
void setLetter(std::string letter) { _letter = letter; }
};
std::istream& operator>>(std::istream& is, X &x) {
std::string str;
std::string letter;
int number;
std::getline(is, str);
sscanf(str.c_str(), "%[^,], %d", letter, &number);A
X c(number, letter);
return is;
}
std::ostream& operator<<(std::ostream& out, X &x) {
out << x.getLetter() << ", " << x.getNum();
return out;
}
int main(int argc,char *argv[]) {
X c1 = X(2, "w");
X c2 = X(6, "c");
X c3, c4;
std::ofstream outFile;
if (!(argc > 1)) return -1;
outFile.open(argv[1]);
std::stringstream str;
str << c1 << std::endl << c2 << std::endl;
std::string xs = xs.c_str();
outFile << xs.c_str();
outFile.close()
std::ifstream infile;
infile.open(argv[1]);
infile >> c3;
infile >> c4;
return 0;
}
I know I'm doing it wrong, and I wanted to know the best way to do it, using std::stringstream to save it in a file, and creating 2 new X's, c3 and c4, using information from c1 and c2.