【发布时间】:2020-07-04 08:16:45
【问题描述】:
我正在制作一个处理点和文件的程序。我没有任何警告或错误,但它仍然无法正常工作。 我认为问题出在 ifstream 上,因为 ofstream 运行良好并将输入的值放入文件中。
我得到的输出是这样的
Please enter seven (x,y) pairs:
//here the seven pairs are entered
These are your points:
//(...,...)x7 with the values
These are the points read from the file:
//and the program ends and returns 0
我希望有人可以帮助我。 这是我的代码。
#include <iostream>
#include "std_lib_facilities.h"
using namespace std;
struct Point{
float x;
float y;
};
istream& operator>>(istream& is, Point& p)
{
return is >> p.x >> p.y;
}
ostream& operator<<(ostream& os, Point& p)
{
return os << '(' << p.x << ',' << p.y << ')';
}
void f() {
vector<Point> original_points;
cout << "Please enter seven (x,y) pairs: " << endl;
for (Point p; original_points.size() < 7;) {
cin >> p;
original_points.push_back(p);
}
cout << endl;
cout << "These are your points: " << endl;
for (int i=0; i < 7; i++) {
cout << original_points[i] << endl;
}
string name = "mydata.txt";
ofstream ost {name};
if (!ost) error("can't open output file", name);
for (Point p : original_points) {
ost << '(' << p.x << ',' << p.y << ')' << endl;
}
ost.close();
ifstream ist{name};
if (!ist) error("can't open input file", name);
vector<Point> processed_points;
for (Point p; ist >> p;) {
processed_points.push_back(p);
}
cout << endl;
cout << "These are the points read from the file: " << endl;
for (int i=1; i <= processed_points.size(); i++) {
cout << processed_points[i] << endl;
}
}
int main()
{
f();
return 0;
}
【问题讨论】:
-
for (int i=1; i <= processed_points.size(); i++) {这是关闭 1 错误吗?记住 c++ 中的数组索引是 0 .. size-1,同样适用于 std::vector -
带有大写字母的向量是一个错字。
-
当我将 i=1 更改为 i=0 时出现范围错误
-
for (int i=1; i <= processed_points.size(); i++) {应该是for (int i=0; i < processed_points.size(); i++) {或者只使用基于范围的 for 循环。请参阅本文底部的示例:https://en.cppreference.com/w/cpp/language/range-for -
非常感谢!!!!!!!现在可以使用了