0

I am trying to read a txt file and store them into array. But i have been getting stof error. I think it due to my fileName but not really sure why.

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

int main() {
    //Define variables
    std::string time, signal1, signal2, signal3;
    std::vector<float> t;
    std::vector<float> s1;
    std::vector<float> s2;
    std::vector<float> s3;

    //Number of sample point
    int i = 0;

    std::fstream file;
    std::string fileName = "example.txt"; // File directory
    file.open(fileName, std::ios::in);

    if (file.is_open()){
        while (!file.eof()){
            getline(file, time, '\t');
            t.push_back(std::stof(time));
            getline(file, signal1, '\t');
            s1.push_back(std::stof(signal1));
            getline(file, signal2, '\t');
            s2.push_back(std::stof(signal2));
            getline(file, signal3, '\n');
            s3.push_back(std::stof(signal3));

            i += 1; //increment of sample
        }
        file.close(); //close file
    }
    else std::cout << "Cannot open file";
    std::cout << "Time" << "\t" << "Signal 1" << "\t" << "Signal 2" << "\t" << "Signal 3" ;

    float signal_1, signal_2, signal_3;
    for (int j=0 ; j<i ;j++)
    {
        std:: cout << t[j] << "\t" << s1[j] << "\t" << s2[j] << "\t" << s3[j];

        if (t[j] == 0){
            signal_1 = s1[j];
            signal_2 = s2[j];
            signal_3 = s3[j];
        }   
    }
    return 0;
}

My data look something like this. The 1st colum is time and the rest is signal 1 2 3.

4.300001789e+001  -1.638320461e-002   -5.628263112e-003   7.854359224e-003
4.300001889e+001  -3.289270774e-002   -5.720957648e-003   3.515933827e-002
4.300001989e+001  -3.685175255e-002   -3.973797895e-003   5.988227949e-002
4.300002089e+001  -2.672457695e-002   -2.672429546e-004   6.607708335e-002
4.300002189e+001  -6.401311141e-003   3.245674074e-003    5.357947573e-002
Sheng
  • 13
  • 1
  • 1
    [`while(!file.eof)` is wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). Probably that caues the error. – churill Dec 05 '20 at 17:33

0 Answers0