使用 ifstream 从文件中读取数据并将其存储在数组中
Using ifstream to read in the data from a file and store it in the array
我有一个文本文件,看起来像这样:
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;
}
}
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组