字符串类 C++ 的重载>>运算符

overloading >> operator for string class c++

本文关键字:gt 运算符 重载 C++ 字符串      更新时间:2023-10-16

我在字符串类的重载>>运算符时遇到问题;这是我的班级:

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);
};

这是重载运算符:

istream& operator >> (istream& in, str& a)
{
    in>>a.s;
    return in;
}

问题是它只读取字符串到第一个空格(句子中只有一个单词)。

我解决了。在dreamincode上找到了答案:D

operator>>的行为是读取到第一个空格字符。将函数更改为以下内容:

istream& operator >> (istream& in, str& a)
{
    in.getline( a.s, sizeof(a.s) );
    return in;
}

istream 类的重载运算符>>() 只接受输入,直到找到任何空格(制表符、换行符、空格字符)。您需要使用 getline 方法。

...
istream& operator >> (istream& in, str& a)
{
    in.getline(a.s, 250);
    return in;
}
...
这就是它的工作原理,你可能想使用 std::getline(std::istream&,std::string&) of std::

getline(std::istream&,std::string&,char)。

编辑:其他人,暗示istreamgetline也是对的。