gpt4 book ai didi

C++如何从文件中读取 float 并将其存储到另一个文件中?

转载 作者:行者123 更新时间:2023-11-28 07:37:25 24 4
gpt4 key购买 nike

输入文件中的数据如下所示:

1.000000 1:-3.2373646522239929e-01 2:-1.5261189913863873e-01 3:-4.0453821036738907e-01 4:-9.8842543217420240e-02 5:-4.1 887499732943145e-01
1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:-5.0017286144749984e-01 4:-9.8842543217420240e-02 5:-4.453 7586918356681e-01
-1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:6.8569681194587440e-01 4:-9.8842543217420240e-02 5:-4.4537 586918356681e-01
-1.000000 1:9.8079913774222305e-01 2:-1.7667120048643550e-01 3:7.3635045033165092e-02 4:-9.8842543217420240e-02 5:-4.45375 86918356681e-01
1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:8.5783918389007385e-01 4:-9.8842543217420240e-02 5:-1.4061 584286101073e-01

如何仅读取 1.000000 或 -1.000000 的第一行 float 并将其存储到数组中并写入另一个文件?这是我编码的内容:

但是当我编译并运行它时,我总是得到随机 float ,而不是 -1.000000 或 1.0000000,请帮助我修复它!

#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
#include <stdio.h>

using namespace std;
int main()
{
ifstream inf;
ofstream outTo;

const char inputFile[] = "input.txt"; //read file from here
const char classFile[] = "classifier.txt";//output to this new file
inf.open(inputFile);
outTo.open(classFile);

float tempVar[5];
float vr;
if(!inf)
{
cout << "Error in opening input.txt" << endl;
exit(1);
}
for( int i = 0; i < 5; ++i)
{
inf >> vr;
if((vr <= 1.009999 && vr >= .990000) || (vr >= -1.009999 && vr <= -0.990000))
tempVar[i] == vr;
inf.ignore(10000, '\n');
}
for (int i = 0; i < 5; ++i)
{
outTo << tempVar[i] << endl;
cout << endl;
}
return 0;
}

最佳答案

考虑到你上面的评论,我建议如下。

#include <sstream>
#include <string>
#include <vector>

// Open file, make sure it's open...

vector<float> floats;
string line;
while (getline(inf, line)){
istringstream iss(line);
float val;
iss >> val;
floats.push_back(val);
}

// show your output

关于C++如何从文件中读取 float 并将其存储到另一个文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500831/

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