[英]C++ how do I read a floating point from the file and store into another file?
输入文件中的数据如下所示:
1.000000 1:-3.2373646522239929e-01 2:-1.5261189913863873e-01 3:-4.0453821036738907e-01 4:-9.8842543217420240e-02 5:-4.1887499732943145e-01
1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:-5.0017286144749984e-01 4:-9.8842543217420240e-02 5:-4.4537586918356681e-01
-1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:6.8569681194587440e-01 4:-9.8842543217420240e-02 5:-4.4537586918356681e-01
-1.000000 1:9.8079913774222305e-01 2:-1.7667120048643550e-01 3:7.3635045033165092e-02 4:-9.8842543217420240e-02 5:-4.4537586918356681e-01
1.000000 1:-3.2373646522239929e-01 2:-1.7667120048643550e-01 3:8.5783918389007385ee-01 4:-9.8842543217420240e-02 5:-1.4061584286101073073e-01
我如何只读取第一行浮点数的每一行(要么是1.000000要么是-1.000000)并存储到数组中并写入另一个文件? 这是我编写的代码:
但是当我编译并运行它时,我总是得到随机浮点数,而不是-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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.