summaryrefslogtreecommitdiffstats
path: root/misc/ofstream-issue/ofstream-issue.cpp
diff options
context:
space:
mode:
authorMitsuo Tokumori <[email protected]>2023-08-18 17:45:56 -0500
committerMitsuo Tokumori <[email protected]>2023-08-18 17:45:56 -0500
commit943677f84eae9e3014a8bfd8613359b0b3189e08 (patch)
treea66c058c935339e694d866adfae8e0ee94de2865 /misc/ofstream-issue/ofstream-issue.cpp
parent387642ff612de7d0ebf09410cd8e39a4765c877a (diff)
downloadLP1-943677f84eae9e3014a8bfd8613359b0b3189e08.tar.gz
LP1-943677f84eae9e3014a8bfd8613359b0b3189e08.tar.bz2
LP1-943677f84eae9e3014a8bfd8613359b0b3189e08.zip
Add miscelaneous directory. Add ifstream-issue...
... there. The parent class should be used to overload the << (or >>) operators for ostream (or istream ). Using ifstream is bad and leads to issues as shown in the example code.
Diffstat (limited to 'misc/ofstream-issue/ofstream-issue.cpp')
-rw-r--r--misc/ofstream-issue/ofstream-issue.cpp47
1 files changed, 47 insertions, 0 deletions
diff --git a/misc/ofstream-issue/ofstream-issue.cpp b/misc/ofstream-issue/ofstream-issue.cpp
new file mode 100644
index 0000000..094e0dd
--- /dev/null
+++ b/misc/ofstream-issue/ofstream-issue.cpp
@@ -0,0 +1,47 @@
+#include <iostream>
+#include <fstream>
+#include <typeinfo>
+
+#define MAXLEN 100
+
+using namespace std;
+
+/* Usando ostream (stream) */
+typedef struct {
+ int id;
+ const char name[MAXLEN];
+} student1_t;
+
+ostream& operator<<(ostream& os, student1_t rhs) {
+ os << "Student name: " << rhs.name;
+ return os;
+}
+
+/* Usando oftream (file) */
+typedef struct {
+ int id;
+ const char name[MAXLEN];
+} student2_t;
+
+ofstream& operator<<(ofstream& os, student2_t rhs) {
+ os << "Student name: " << rhs.name;
+ return os;
+}
+
+int main() {
+ ofstream out("report.txt");
+ if (!out) {
+ cerr << "Error: no se pudo abrir el archivo\n";
+ return 1;
+ }
+ student1_t student1 = {1, "Ana Ambooken"};
+ student2_t student2 = {2, "Bob Banana"};
+
+ out << student1 << "PUCP" << '\n'; // works
+ out << "PUCP" << student1 << '\n'; // works
+
+ out << student2 << "PUCP" << '\n'; // works
+ /* out << "PUCP" << student2 << '\n'; // breaks */
+
+ return 0;
+}