字符串类 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;
}
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)。
编辑:其他人,暗示istream
的getline
也是对的。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 是否需要使用 - &gt;运算符在C 中调用成员函数时