【发布时间】:2014-02-27 15:13:05
【问题描述】:
我正在尝试在将文件加载到数组后打印出文件的内容。我正在打印第一个条目,但其余的都输出为 0。我觉得我需要在某个地方放置另一个循环,但我不确定它在哪里工作得最好。
这是我的代码:
#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;
};
void populate (plane planeArray[], int n )
{
string name, direction;
int id, coordX, coordY, height, speed, i, c;
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++ )
{
getline(infile, planeArray[i].name);
infile >> planeArray[i].id;
infile >> planeArray[i].coordX;
infile >> planeArray[i].coordY;
infile >> planeArray[i].height;
infile >> planeArray[i].speed;
getline(infile, planeArray[i].direction);
}
infile.close();
}
void text_display( plane planeArray[5])
{
for ( int i = 0; i < 4; i++ )
{
cout << planeArray[i].name << endl;
cout << planeArray[i].direction << 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;;
cout << endl;
}
}
int main()
{
const int N = 5;
plane planeArray[N] = {};
populate( planeArray, N );
text_display( planeArray);
}
这是文件中包含的内容:
Airbus A380
123456
123 300
25000
400
north
Boeing-747
140
234567
30000
450
north west
Cessna-404-Titan
345678
145
29000
400
south
Sukhoi-Superjet-100
456789
120
28000
300
south west
Lockheed-Jetstar
567890
270
20000
500
east
这是我运行代码时得到的输出:
Airbus A380
123456
123
300
25000
400
north
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Process returned 0 (0x0) execution time : 0.090 s
Press any key to continue.
非常感谢任何帮助! (另外,如果你能告诉我如何去掉打印数据中第一个和最后一个条目周围的空白行,那将是一个不错的奖励。)
干杯
【问题讨论】:
-
在每次循环迭代之间,您应该检查流是否处于错误状态;