【发布时间】:2016-11-13 15:08:48
【问题描述】:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
struct Point
{
double x;
double y;
};
istream& operator>>(istream& is, Point& p)
{
char ch;
if(is >> ch && ch != '(')
{
is.unget();
is.clear(ios_base::failbit);
return is;
}
char ch2;
double x;
double y;
is >> x >> ch >> y >> ch2;
if(!is || ch != ';' || ch2 != ')')
{
cerr << "Error: Bad record!\n";
exit(1);
}
p.x = x;
p.y = y;
}
ostream& operator<<(ostream& os, const Point& p)
{
return os << '(' << p.x
<< ';' << p.y << ')' << endl;
}
int main()
{
Point p;
vector<Point> original_points;
cout << "Please enter 3 points:\n";
for(int i = 0; i < 3; ++i)
{
cin >> p;
original_points.push_back(p);
}
cout << "\nYou've entered:\n";
for(Point x : original_points)
cout << x;
ofstream ost{"mydata"};
for(Point x : original_points)
ost << x;
ost.close();
vector<Point> processed_points;
ifstream ist{"mydata"};
while(ist >> p)
processed_points.push_back(p);
ist.close();
cout << "original_points: ";
for(Point x : original_points)
cout << x;
cout << "processed_points: ";
for(Point x : original_points)
cout << x;
if(original_points.size() != processed_points.size())
cout << "Oops! Seems like something went wrong!\n";
return 0;
}
经过调试发现错误是由这行代码引起的:
while(ist >> p)
这部分代码几乎 100% 抄自书中:
istream& operator>>(istream& is, Point& p)
{
char ch;
if(is >> ch && ch != '(')
{
is.unget();
is.clear(ios_base::failbit);
return is;
}
char ch2;
double x;
double y;
is >> x >> ch >> y >> ch2;
if(!is || ch != ';' || ch2 != ')')
{
cerr << "Error: Bad record!\n";
exit(1);
}
p.x = x;
p.y = y;
}
Google 和 stackoverflow 表示此错误是由于以错误的方式访问内存造成的。我检查了这个代码一个小时,我不知道是什么导致了问题。我今天开始学习流,这是“编程-使用C++的原理和实践(第二版)”第10章的一个练习。
附:对不起我的英语语法,这不是我的母语)
【问题讨论】:
-
您需要进入您的
>>过载,并确定段错误发生的位置。 -
一小时是很短的时间。继续努力。过几天再来。
-
好吧,我在写这段代码的时候只有纯控制台。我会遵循上面的建议,希望能发布解决方案。