#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++을 사용하는 원리와 실습 (제 2 판)"제 10 장에서의 연습입니다.
P. 내 영어 문법에 대한 죄송합니다, 그렇지 최종 값을 반환하는 기능 operator>>(istream& is, Point& p)
리드 코드의 모든 지점은 그래서 당신은 함수의 끝에서 값 return is;
을 반환 푸시를 분실하고 있다고 가정 내 모국어)
당신은'''과부하 상태로 들어가서 segfault가 발생하는 곳을 결정해야합니다. –
시간은 매우 짧은 시간입니다. 계속 일해라. 며칠 후에 다시 오십시오. –
좋아요,이 코드를 작성할 때 저는 순수 콘솔을 가지고있었습니다. 위의 조언을 따르고 해결책을 게시 해 드리겠습니다. – SweetYogurt