在重载复杂类的运算符>>时发生分段错误
occurs segmentation fault while overloading operator >> for the Complex class
如果我想在我的 c++ 程序中使用这样的句子,
while (cin >> c)
{
cout << c << endl;
}
c 是我之前定义的一个复杂类。
如何重载复杂类的运算符>> 我尝试了两种方法,但是当程序第二次运行上述句子cin>>c时,由于分割错误,它们都失败了,and the first method is
friend istream& operator >> (istream& in, Complex& right)
{
char a;
char temp[50];
int cnt = 0;
double i = 0;
double r = 0;
while (in >> a)
{
if (a == ')')
{
temp[cnt] = a;
break;
}
temp[cnt++] = a;
}
sscanf(temp, "(%lf,%lf)", &r, &i);
right.real = r;
right.imag = i;
}
第二种方法是
friend istream& operator >> (istream& in, Complex& right)
{
double r = 0;
double i = 0;
in.ignore();
in >> r;
in.ignore();
in >> i;
in.ignore();
right.real = r;
right.imag = i;
}
我的输入是这样的 (1.5,2)(1,2.5)(1.5,2.5)(0,0)(1,2)
谁能给出一些提示?在 temp 末尾添加 nullptr 后,
我仍然遇到同样的问题,以下是错误
程序接收信号SIGSEGV,分段错误。 主.cpp:75 的 f () 中的0x0000000000401285 75 同时 (CIN>> c) (GDB) S
问题很可能是您使用不以 null 结尾的字符串调用sscanf
。
while (in >> a)
{
if (a == ')')
{
temp[cnt] = a;
break;
}
temp[cnt++] = a;
}
// Need to null terminate temp
temp[cnt+1] = ' ';
sscanf(temp, "(%lf,%lf)", &r, &i);
首先,它是operator>>
而不是operator >>
(注意缺少空格)。
其次,为什么不只是这个:
friend istream& operator>> (istream& in, Complex& right)
{
in >> right.real;
in >> right.imag;
}
注意:您还必须重载operator<<
才能cout << c << endl
工作。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- EASTL矢量<向量<int>>连续的
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?