gpt4 book ai didi

c++ - 导入文件 txt 时出错

转载 作者:行者123 更新时间:2023-11-28 02:22:46 27 4
gpt4 key购买 nike

<分区>

我有一个关于导入简单文本的问题(这是一本书的练习)。我能够导出自定义类型 Point 的 vector 值,但我无法读回它们并将它们存储在另一个 vector 中。我跑了很多次试图了解可能是什么原因,我看到在 while 循环中程序构建了 vector ,但是当它结束时它给了我一个 run_time_error。我猜它不识别文件结尾。这些是我的文件:

头文件:

class Point
{
private:
int x, y;
public:
Point();
Point(int x1, int y1);
int get_x() const { return x; }
int get_y() const { return y; }
void print_all(const vector<Point>& pv);
void import_all(vector<Point>& pv);
Point operator=(const Point& p);
};

istream& operator>>(istream& is, Point& p);
ostream& operator<<(ostream& os, const Point& p);
ostream& operator<<(ostream& os, const vector<Point>& p);

源文件:

#include "stdafx.h"
#include "std_lib_facilities.h"
#include "wfile.h"

Point::Point()
: x{ 0 }, y{ 0 } {}

Point::Point(int x1, int y1)
: x{ x1 }, y{ y1 } {}

Point Point::operator=(const Point& p)
{
x = p.get_x(); y = p.get_y();
return *this;
}

ostream& operator<<(ostream& os, const Point& p)
{
return os << '(' << p.get_x() << ','
<< p.get_y() << ')' << endl;
}

ostream& operator<<(ostream& os, const vector<Point>& p)
{
for (int i = 0; i < p.size(); ++i)
{
cout << i + 1 << ")" << " "
<< "X: " << p[i].get_x() << " " << "Y: " << p[i].get_y() << endl;
}

return os;
}

istream& operator>>(istream& is, Point& p)
{
int x, y;
is >> x >> y;
if (!is)
{
error("Bad input.");
is.clear(ios::failbit);
is.unget();
return is;
};

p = Point(x, y);

return is;
}

void Point::print_all(const vector<Point>& pv)
{

cout << "Please enter file output name: " << endl;
string oname;
cin >> oname;
ofstream ost{ oname };
if (!ost) error("Can't open output file.", oname);

for (int i = 0; i < pv.size(); ++i)
{
ost << pv[i].get_x() << " " << pv[i].get_y() << endl;
}
}

void Point::import_all(vector<Point>& pv)
{

cout << "Please enter file input name: " << endl;
string iname;
cin >> iname;
ifstream ist{ iname };
if (!ist) error("Can't read file, ", iname);
while (true)
{
Point p;
if (!(ist >> p)) break;
pv.push_back(p);
}
}

主文件:

// Work with external files.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "std_lib_facilities.h"
#include "wfile.h"


int main()
{
Point p;
vector<Point> original_points;
vector<Point> processed_points;

cout << "Please enter 7 pairs of numbers: " << endl;

for (int i = 0; i <= 6; ++i)
{
cout << "#" << i + 1 << " pair: ";
cin >> p;

original_points.push_back(p);
}

p.print_all(original_points);

cout << original_points << endl;

p.import_all(processed_points);

cout << processed_points << endl;

keep_window_open();

return 0;
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com