【发布时间】:2014-02-25 18:24:55
【问题描述】:
我正在使用一个函数从一个文本文件中填充一个数组。据我所知,数组填充得很好,但是当我使用 cout 打印数组时,我得到了很多错误,说明文件中的数据无法转换为不同的数据类型(如果这些错误是需要,评论让我知道)。
我目前的代码是:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
struct plane //strcutre of plane data to use
{
string name;
string direction;
int id;
int coordX;
int coordY;
int height;
int speed;
};
int populate (plane planeArray[5])
{
string name, direction;
int id, coordX, coordY, height, speed, i;
ifstream infile; //declare input file stream
infile.open("plane_data.txt"); //opens file
if (!infile)
{
cout << "File cannot be reached"; //checks for invalid file path
}
for (int i = 0; i < 4; i++){
infile >> planeArray.name[i];
infile >> planeArray.direction[i];
infile >> planeArray.id[i];
infile >> planeArray.coordX[i];
infile >> planeArray.coordY[i];
infile >> planeArray.height[i];
infile >> planeArray.speed[i];
}
infile.close();
}
void text_display(plane planeArray[5])
{
for (int i = 0; i < 4; i++)
{
cout << planeArray[i].name << endl;
cout << planeArray[i].id << endl;
cout << planeArray[i].coordX << endl;
cout << planeArray[i].coordY << endl;
cout << planeArray[i].height << endl;
cout << planeArray[i].speed << endl;
}
}
int main() {
plane planeArray[5];
populate( planeArray);
//text_display( planesArray);
};
感谢任何输入!
干杯
【问题讨论】:
-
您永远不会用文件中的数据填充数组,也永远不会为
plane实现operator<<。基本上你的程序什么都不做。 -
你怎么知道数组填充得很好?您的代码似乎没有填充它。它只是用文件中的值覆盖局部变量。
-
如果不先定义
struct plane,就不能使用<<运算符。如果您不想自己定义运算符,请执行cout << playArray[i].name之类的操作。 -
好的,所以我在 couts 之后添加了 .name 等,我不再收到错误但没有打印。