【发布时间】:2014-09-11 18:23:21
【问题描述】:
这是C++编程原理与实践第10章的练习。 该程序使用积分:
- 它提示用户输入 (x,y) 对。然后将它们存储在称为
original_points的点向量中。 - 原始点被打印到文件中
- 然后程序读取文件以检索相同的点,这些点存储在名为
processed_points的点向量中 - 比较两个向量,如果不相同,程序会报错。
问题是processed_points 的size() 为0,只有当我使用get_vector_points() 来获得这些分数时才会发生这种情况。函数有什么问题?
//put any vector points from ist into points
void get_vector_points(istream& ist, vector<Point>& points)
{
//this function is bad, it doesn't do anything the second time you use it
while(true)
{
Point p;
if( ist >> p)
points.push_back(p);
else return;
}
}
//
void write_to_file(string& path, vector<Point>& v_of_points)
{
//open output file
ofstream ofile(path);
//output results to file
for(Point p : v_of_points)
{
ofile << p <<endl;
}
//close output stream
ofile.close();
}
void read_from_file(string& path, vector<Point>& v_of_points)
{
//open input file
ifstream ifile(path);
//read from file : Here comes trouble
get_vector_points(ifile, v_of_points);
//But no problem if you do the following instead
// while(true)
// {
// Point p;
// if( ifile >> p)
// v_of_points.push_back(p);
// else break;
// }
}
//read point from specified istream ist, format:(0,0)
//output points from specified ostream ost, format:(0,0)
void points_drill(string path)
{
//read from console a vector of points
vector<Point> original_points;
get_vector_points(cin, original_points);
//write the same vector to file
write_to_file(path,original_points);
//read the same vector from file, but call it processed
vector<Point> processed_points;
read_from_file(path,original_points);
//they should be the same
for (int i= 0; i < original_points.size(); i++)
{
if (original_points.size()!=processed_points.size())
throw runtime_error("Size Mismatch"); //error here and proccesed_point has size of 0
if (original_points[i]!=processed_points[i])
throw runtime_error("something is wrong!");
}
}
请注意,我使用的是自定义点。完整代码在http://pastebin.com/ZvfcZxf3
对编码风格/可读性的任何评论表示赞赏。
【问题讨论】:
-
get_vector_points从cin读取,而不是从传递给它的流中读取,ist -
好的,我已更正并尝试再次运行它。同样的错误仍然存在。嗯...
-
我刚刚发现另一个错误,我写了
read_from_file(path,original_points);而不是read_from_file(path,processed_points);我不敢相信我错过了它。这就是这个问题的结束。 -
...这正是我五分钟前在回答中所写的
-
我猜是页面部分没有刷新,抱歉