473,378 Members | 1,321 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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 5868
> 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::istringstream 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::istringstream sstream (s);
sstream >> result;
return result;
}

std::string x_to_string (const X & x)
{
std::ostringstream 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
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
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...
6
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...
5
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...
2
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
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...
0
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...
4
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
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.