Reputation: 115
I have a problem with overloading >> operator for string class; here is my class:
class str
{
char s[250];
public:
friend istream& operator >> (istream& is, str& a);
friend ostream& operator << (ostream& os, str& a);
friend str operator + (str a, str b);
str * operator = (str a);
friend int operator == (str a, str b);
friend int operator != (str a, str b);
friend int operator > (str a, str b);
friend int operator < (str a, str b);
friend int operator >= (str a, str b);
friend int operator <= (str a, str b);
};
and here is overloaded operator:
istream& operator >> (istream& in, str& a)
{
in>>a.s;
return in;
}
the problem is that it reads the string only to first space(only one word from sentence).
I solved it. Found the answer on dreamincode :D
Upvotes: 1
Views: 6925
Reputation: 143289
That's how it works, you probably want to use std::getline(std::istream&,std::string&) of std::getline(std::istream&,std::string&,char).
edit: others, suggesting istream
's getline
are also right.
Upvotes: 1
Reputation: 109289
The behavior for operator>>
is to read until the first whitespace character. Change your function to the following:
istream& operator >> (istream& in, str& a)
{
in.getline( a.s, sizeof(a.s) );
return in;
}
Upvotes: 3
Reputation: 423
The overloaded operator>>() for the istream class just takes the input till it finds any blank space (tab, newline, space characters). You need to use the getline method.
...
istream& operator >> (istream& in, str& a)
{
in.getline(a.s, 250);
return in;
}
...
Upvotes: 1