c++ - 从 C++ 中的文件加载的数组中获取输出

标签 c++ arrays loops

我试图在文件加载到数组后打印出文件的内容。我正在打印第一个条目,但其余的都输出为 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.

非常感谢任何帮助! (另外,如果你能告诉我如何去掉打印数据中第一个和最后一个条目周围的空白行,那将是一个很好的奖励。)

干杯

最佳答案

文件中的 block 之间有一个空行,您可以忽略它。

读取第一个 block 并移动到第二个 block 后,文件位置仍然在空行的前面。您对第二个 block 的读取与实际数据相差一行。

这意味着您正在读取 planeArray[1].name 的空行,然后尝试从 Boeing-747 行读取到 planeArray[ 1].id 这将失败,因为格式与 int 不匹配。此时流进入错误状态,之后不再读取任何内容。

这可以通过在循环结束时向虚拟字符串添加额外的 getline 来解决。

您的文件还缺少除第一个以外的所有 block 的第二个坐标,这将导致类似的问题。

关于c++ - 从 C++ 中的文件加载的数组中获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22072590/

相关文章:

c++ - 为什么在重建解决方案后构建速度更快?

c++ - 在 C++ 中存储和操作大量数据的想法

c++ - C/C++ 解析器/词法分析器如何区分指针的 '*' 和乘法的 '*'?

arrays - 使用 reduce 或 joined 组合数组有什么区别?

java - 两个条件的 while 循环

c++ - 所有 LLVM 层的用途是什么?

php - 使用 PHP 在 mysql 查询中创建动态 AND 子句

ios - 如何在 Swift 中从数组中的数组中获取字符串

javascript - 遍历包含图像的数组并删除带有错误 Javascript 的图像

r - 如何对每个样本的多个观察值中的变量进行分箱?