Janni Nevill
Janni Nevill

Reputation: 37

C++ how do I read a floating point from the file and store into another file?

The data in the input file looks like:

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.5783918389007385e-01 4:-9.8842543217420240e-02 5:-1.4061584286101073e-01

How do I read each line of fist float number either 1.000000 or -1.000000 only and store into the array and write to another file? Here is what I coded:

but when I compiled and run it, I always get random float point, instead of either -1.000000 or 1.0000000, please help me to fix it!

#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;
}

Upvotes: 0

Views: 2075

Answers (1)

kenrogers
kenrogers

Reputation: 1350

Taking your comment above into question, I'd recommend something like the following.

#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

Upvotes: 1

Related Questions