gpt4 book ai didi

c++ - 读取文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:35 27 4
gpt4 key购买 nike

我的文本文件如下所示:

1 41 -1 -1.492 -2.9555
1 42 -1 -1.49515 -2.9745
1 43 -1 -1.49799 -2.99361
1 44 -1 -1.50051 -3.01283
1 45 -1 -1.5027 -3.03213
1 46 -1 -1.50416 -3.05301
1 47 -1 -1.50556 -3.07248

(数字之间用空格分隔,而不是制表符。)

我想用 C++ 编写一个程序来读取这些值并将它们放入 vector 中,但我该怎么做呢?

我试过这个:

while(!file.eof()){
scanf("%d %d %d %f %f", &x, &y, &z, &eta, &phi);
}

但它不起作用。

谁能告诉我为什么以及如何解决这个问题?

最佳答案

你在 C++ 所以不要使用 scanf , 更喜欢 std::ifstream相反。

#include <fstream>
using namespace std;

ifstream file("input.txt");
int x, y, z;
float eta, phi;
// Read you file until the end
while( file >> x >> y >> z >> eta >> phi )
{
// Print the values
cout << "x : " << x << " y :" << y << " z : " << z << " eta : " << eta << " phi : " << phi << endl;
}

如 Armen Tsirunyan 所示,您还可以使用 structvector 存储数据.这取决于您要对数据做什么。

结构的优点是您有一个实体代表所有数据。你可以重载 operator>>以更清晰的代码读取文件。

代码看起来像这样:

#include <fstream>
#include <vector>
using namespace std;

struct s_Data
{
int x, y, z;
float eta, phi;
};

istream& operator >> (istream& iIn, s_Data& iData)
{
return iIn >> iData.x >> iData.y >> iData.z >> iData.eta >> iData.phi;
}

ifstream file("input.txt");
// Read you file until the end
s_Data data;
vector<s_Data> datas;
while( file >> data )
{
// Print the values
cout << "x : " << data.x << " y :" << data.y << " z : " << data.z << " eta : " << data.eta << " phi : " << data.phi << endl;

// Store the values
datas.push_back( data );
}

在这里s_Data用你想要的 5 个值代表你的 lign。 vector<s_Data>代表文件中读取的所有值。您可以通过以下方式阅读它:

unsigned int size = datas.size();
for ( unsigned int i = 0; i < size; i++ )
cout << datas[i].x; // read all the x values for example

关于c++ - 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17484317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com