473,661 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

object to standard output and input ( cout / cin )

suppose i have a class:
class X
{
int i;
string out;
}

X::out = "object x";
how can i do this:
code:
X obj;
cout<<obj;

output:
objext x
and

code:
X obj;
cin>>obj

is this possible???

thanks. =)

Jul 22 '05 #1
3 5891
> cout<<obj;
cin>>obj

is this possible???

sure...operator overloading. there are tons of c++ textbook examples
on this.

Jul 22 '05 #2
gouki wrote:
suppose i have a class:
class X
{
int i;
string out;
}
You forgot the semicolon. Also, the class is unusable because it has no
friends and no public members. Assume you have this instead:

// Header file "X.h"

#include <iosfwd>
#include <string>

class X
{
int i;
std::string out;

// These will come in handy later.
friend std::ostream & operator << (std::ostream &, const X &);
friend std::istream & operator >> (std::istream &, X &);

public:
X (int i, const std::string & out) : i (i), out (out) { }
};
X::out = "object x";
(Another syntax error. As a non-static member of X, out can only be
accessed for a particular X object, using the . or -> operator.)
how can i do this:
code:
X obj;
cout<<obj;

output:
objext x
and

code:
X obj;
cin>>obj

is this possible???


Yep. Overload the << and >> operators. Here's your first draft. This is
not well-tested code, and it artificially constrains X (if an X object
is to be successfully streamed out and then back in again, the "out"
member cannot contain a newline), but you get the idea.

// Source file X_io.cpp

#include "X.h"
#include <ostream>
#include <istream>
#include <sstream>

std::ostream & operator << (std::ostream & stream, const X & x)
{
return stream << x.i << '\n' << x.out << '\n';

// That was easy!
}

std::istream & operator >> (std::istream & stream, X & x)
{
// For extractors we usually have to work a bit harder.

int i;
std::string out;

// Read 'i' and 'out' as single lines from 'stream'.

{
std::string t;
std::getline (stream, t);
std::istringstr eam sstream (t);
sstream >> i;
}
std::getline (stream, out); // Read "out".

// Commit results if no stream error.

if (stream)
{
x.i = i;
x.out.swap (out); // We can't risk a bad_alloc at this stage.
}
return stream;
}

// Source file "test.cpp"

#include "X.h"
#include <string>
#include <sstream>
#include <iostream>
#include <cstddef>

X x_from_string (const std::string & s)
{
X result (0, "");
std::istringstr eam sstream (s);
sstream >> result;
return result;
}

std::string x_to_string (const X & x)
{
std::ostringstr eam sstream;
sstream << x;
return sstream.str ();
}

int main (int argc, char * argv [])
{
std::string persistent;

{
X old (163, "262 537 412 640 768 744");
persistent = x_to_string (old);
}

X lazarus (x_from_string (persistent));

std::cout << lazarus;
return EXIT_SUCCESS;
}

--
Regards,
Buster.
Jul 22 '05 #3
On 5 Aug 2004 18:51:08 -0700 in comp.lang.c++, "gouki"
<fi*****@gmail. com> wrote,
how can i do this:
code:
X obj;
cout<<obj;


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[15.8] How can I provide printing for my class Fred? " It is always
good to check the FAQ before posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/

Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1272
by: Grumble | last post by:
Hello, I was recently told that there were <quote>a lot of things wrong</quote> with the following program: #include <iostream> int main() { cout << '\a';
5
1770
by: August1 | last post by:
This is a short program that I have written from a text that demonstrates a class object variable created on the stack memory and another class object variable created on the heap memory. By way of the text, the program is supposed to demonstrate the use of a copy constructor function for the object created on the heap (because there is a char* pointer variable in the instantiated class) and how you would use the delete keyword with the...
6
2365
by: surrealtrauma | last post by:
i have a trouble about that: i want to ask user to enter the employee data (employee no., name, worked hour, etc.), but i dont know how to sort the data related to a particular employee as a group. i want to use a array object in the class but i don't know how..i am just learning the c++. So i dont know how to use class. in fact, i have writen like the following: class employee { public: employee();
5
5918
by: surrealtrauma | last post by:
the requirement is : Create a class called Rational (rational.h) for performing arithmetic with fractions. Write a program to test your class. Use Integer variables to represent the private data of the class – the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should...
2
2653
by: qazmlp1209 | last post by:
FAQ at "http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.6" states that the following program will not work properly: --------------- int main() { char name; int age; for (;;)
4
4918
by: Tom | last post by:
I come from C but don't really understand why in C++ you can return a temporary object from a function. For example: class Test { public: Test() { cout << "Address of object: " <<this <<endl; } ~Test() { } };
0
1845
by: lini | last post by:
Hello, I am writing some code in the scenario which can be described as follow: + program A which writes to standard output (e.g. cout >> whatever). + program B which has GUI and also listens to the standart input regularly (using a timer) if there is no input, it returns to the GUI and does something else. What I expect is B should work without problem in both cases: (1) user@host $ A | B (2) user@host $ B In B's code, I tried...
4
3010
by: Philipp.Weissenbacher | last post by:
Hi all! I wrote the following as a test case for a menu based programme: #include <iostream> #include <cstring> using namespace std; #define cls system("cls") const int SIZE = 10;
1
3308
by: terminatorul | last post by:
Hello Sorry if asking a known question. I have a program that reads lines of text from standard input and writes the non-empty ones back to standard output. In most cases it will be used with standard input and output streams redirected to FS files. If my input is wide-character (UNICODE) I would like to use wcin and wcout and write wide-character text to standard output. If my input is
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8343
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.