我在istream中有此格式化的字符串。带格式字符串的istream抽取值
(5,-4)
让说:
- 开括号
- 的整数
- 逗号和空格
- 另一个整数
- 右括号
我想知道什么是提取两个整数和验证字符串格式的最佳方法。
这是这样一类:
class MyPoint
{
public:
MyPoint() = default;
~MyPoint() = default;
...
friend ostream & operator>>(ostream & lhs, MyPoint const & rhs);
...
private:
int x, y;
};
ostream & operator>>(ostream & lhs, MyPoint const & rhs) {
// ???
}
非常感谢大家。
这里是我的头文件
#ifndef MYPOINT_H
#define MYPOINT_H
#include <iostream>
using namespace std;
class MyPoint
{
public:
MyPoint() : mX{ 0 }, mY{ 0 } { ; }
MyPoint(int x, int y) : mX{ x }, mY{ y } { ; }
~MyPoint() = default;
int x() const { return mX; }
int y() const { return mY; }
void setX(int x) { mX = x; }
void setY(int y) { mY = y; }
MyPoint operator-() const { return MyPoint(-mX, mY); }
MyPoint operator+(MyPoint rhs) const { rhs.mX += mX; rhs.mY += mY; return rhs; }
MyPoint operator-(MyPoint rhs) const { rhs.mX = mX - rhs.mX; rhs.mY = mY - rhs.mY; return rhs; }
MyPoint operator*(MyPoint rhs) const { rhs.mX *= mX; rhs.mY *= mY; return rhs; }
MyPoint operator/(MyPoint rhs) const { rhs.mX = mX/rhs.mX; rhs.mY = mY/rhs.mY; return rhs; }
MyPoint operator%(MyPoint rhs) const { rhs.mX = mX % rhs.mX; rhs.mY = mY % rhs.mY; return rhs; }
friend MyPoint operator+(int lhs, MyPoint const & rhs);
friend MyPoint operator-(int lhs, MyPoint const & rhs);
friend MyPoint operator*(int lhs, MyPoint const & rhs);
friend MyPoint operator/(int lhs, MyPoint const & rhs);
friend MyPoint operator%(int lhs, MyPoint const & rhs);
friend ostream & operator<<(ostream & lhs, MyPoint const & rhs);
friend istream & operator>>(istream & lhs, MyPoint & rhs);
private:
int mX, mY;
};
#endif //MYPOINT_H
在这里,我的源文件
#include "MyPoint.h"
MyPoint operator+(int lhs, MyPoint const & rhs) {
return MyPoint(lhs + rhs.mX, lhs + rhs.mY);
}
MyPoint operator-(int lhs, MyPoint const & rhs) {
return MyPoint(lhs - rhs.mX, lhs - rhs.mY);
}
MyPoint operator*(int lhs, MyPoint const & rhs) {
return MyPoint(lhs * rhs.mX, lhs * rhs.mY);
}
MyPoint operator/(int lhs, MyPoint const & rhs) {
return MyPoint(lhs/rhs.mX, lhs/rhs.mY);
}
MyPoint operator%(int lhs, MyPoint const & rhs) {
return MyPoint(lhs % rhs.mX, lhs % rhs.mY);
}
ostream & operator<<(ostream & lhs, MyPoint const & rhs) {
return lhs << "(" << rhs.mX << "," << rhs.mY << ")";
}
istream & operator >> (istream & lhs, MyPoint & rhs) {
return lhs >> "(" >> rhs.mX >> "," >> rhs.mY >> ")"; // HERE is the compiling error
}
最后,在主
MyPoint p1, p2(2, -2);
cout << p1 << endl;
cout << p2 << endl;
有了这个文件的测试中,我得到了这个错误: 错误C2679二进制“>>”:找不到操作符,它的右边的操作数是ty PE“为const char [2]”(或没有可接受的转化率)
嗨,杰里,这正是我在找的东西 另外,我找不到任何有关此文档技术。我的意思是,如果我想查找关于iostream >>(char *)的信息,请使用什么术语? 非常感谢所有细节! – Aesope
@Aesope:我不知道有很多细节超出这个事实,这只是运营商的另一个超载。有一个现有的重载读取字符串(指向缓冲区)的指针。这只是基于指针的“常量”的另一个重载。在C++上任何一本体面的书籍都应该涵盖对常量的重载。这只是一个众所周知的功能的应用。 –
嗨杰瑞。这是我的想法。同时,我在编译时遇到了一个奇怪的错误。我需要一个特殊的头文件吗?或者是其他东西?我从MSVC++ 2015得到这个编译错误: 错误C2679:二进制'>>':找不到运算符类型'const char [2]'的右边操作数(或没有可接受的转换) – Aesope