[英]how to read file with struct in cpp
我有代码
#include <iostream>
#include <fstream>
using namespace std;
struct triangle
{
float x;
float y;
};
int main() {
float x, y;
struct triangle triangles[100];
ofstream theFile("toado.txt");
for(int index = 0; index < 3 ; index ++) {
cout<<"please enter the coordinates x,y of point in of triangle : "<<endl;
cin>>x>>y;
theFile <<x<<" "<<y<<endl;
}
int i=0;
ifstream fileRead("toado.txt");
while(fileRead >> triangles[i].x >> triangles[i].y) {
i++;
}
cout<<"====================================================================="<<endl<<endl;
for (int index = 0; index < i; index ++) {
cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[i].x<<","<<triangles[i].x<<")"<<endl;
}
cout<<"====================================================================="<<endl<<endl;
return 0;
}
当我输入值时:1、2、3、4、5 6,但输出如下
(-3.97922e-15,-3.97922e-15)(-3.97922e-15,-3.97922e-15)(-3.97922e-15,-3.97922e-15)
您的错误很简单
cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[i].x<<","<<triangles[i].x<<")"<<endl;
应该
cout<<"the coordinates x, y of point "<<index+1<<" : ("<<triangles[index].x<<","<<triangles[index].y<<")"<<endl;
那是
triangles[ i ].x => triangles[ index ].x
并且您两次都打印了x
,所以我将第二个x
固定为y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.