簡體   English   中英

重載>>字符串類C ++的運算符

[英]overloading >> operator for string class c++

我對於字符串類的>>運算符重載有問題; 這是我的課:

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

就是這樣,您可能要使用std :: getline(std :: istream&,std :: string&,char)的std :: getline(std :: istream&,std :: string&)

編輯 :其他人,建議istreamgetline也是正確的。

istream類的重載運算符>>()僅接受輸入,直到找到任何空格(制表符,換行符,空格字符)為止。 您需要使用getline方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM