使用 ifstream 从文件中读取数据并将其存储在数组中

Using ifstream to read in the data from a file and store it in the array

本文关键字:存储 数组 数据 ifstream 文件 读取 使用      更新时间:2023-10-16

我有一个文本文件,看起来像这样:

Mercury     0.39    0
Venus       0.72    0
Earth       1.0 1
Mars        1.52    2
Jupiter     5.2 67
Saturn      9.53    63
Uranus      19.2    27
Neptun      30.1    14

有一个程序从这个文件中读取数据,以便它存储在数组中,它看起来像这样:

/********************************************************************************
 *
 * Planets.cpp: program reads data from the file planets.dat and prints the 
 *              information. Objects of classPlanet are used to store and print
 *              the data
 *
 * Copyright (C) October 2014               Stefan Harfst (University Oldenburg)
 * This program is made freely available with the understanding that every copy
 * of this file must include this header and that it comes without any WITHOUT
 * ANY WARRANTY.
 ********************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include "classPlanet.h"
using namespace std;
int main() {
  Planet planets[8];
  ifstream pdata;
  pdata.open("planets.dat");
  for (int i=0; i<8; ++i) {
    string name;
    double d;
    int    n;
    pdata >> name >> d >> n;
    planets[i] = Planet(name, d, n);
  }
  for (int i=0; i<8; ++i) 
    planets[i].print();
}

如果您帮助我理解"数据>>名称>> d>> n;"这一行,我将不胜感激。为什么名称、d 和 n 的值在每次迭代中都会改变?我们在哪里指定程序应该读入文本文件的哪一行或哪一列?

data >> name >> d >> n首先跳过空格,然后读取字符串,然后跳过空格,然后读取双精度,然后跳过空格,然后读取整数。
它与

data >> name;
data >> d;
data >> n;

您不指定行或列 - 流有一个"当前位置",它会跟踪并从该点读取。
实际上,无法指定要从流中读取的列或行 - 您需要编写自己的代码,将输入分解为行和列。

如果你想获取特定列的内容,最简单的方法是不使用你不感兴趣的列的内容

int main()
{
    ifstream data("planets.dat");
    // Print all the planets' names
    while (data)
    {
        std::string name;
        double d;
        int n;
        data >> name >> d >> n;
        std::cout << name << std::endl;
    }
}