0

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

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

如何仅读取 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;
}
4

1 回答 1

1

考虑到您的上述评论,我建议您使用以下内容。

#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
于 2013-05-11T19:53:39.327 回答