Search code examples
c++ofstream

How to ofstream all values from one variable in one line and all values from the other variable on the other line?


I have this program (c++) that calculates two variables values in a while cycle. I'm trying to wrote these values in a text file. Now I want to write the 5 values of my lforce variable in one line of the text file and the 5 values of my rforce variable in the other line. How can I do that?

int i = 5;
int a2dVal = 0; 
int a2dChannel = 0;
unsigned char data[3];
float g = 9.8;
int fsensor1;
int fsensor2;
int fsensor3;
int fsensor4;
int fsensor5;
int fsensor6;   
float vsensor;
int lforce;
int rforce; 
float vref = 2.5;
float vin = 3.3;

ofstream myfile ("/var/www/html/Sensors/all.txt");


if (myfile.is_open())
{

    while(i > 0)
    {
        data[0] = 1;  //  first byte transmitted -> start bit
        data[1] = 0b1000000000 |( ((a2dChannel & 9) << 4)); // second byte    transmitted -> (SGL/DIF = 1, D2=D1=D0=0)
        data[2] = 0; // third byte transmitted....don't care

        a2d.spiWriteRead(data, sizeof(data) );

        a2dVal = 0;
                a2dVal = (data[1]<< 10) & 0b110000000000; //merge data[1] & data[2] to get result
                a2dVal |=  (data[2] & 0x0f);
        sleep(1);

        vsensor = (vref*a2dVal)/1024;

        fsensor1 = ((vsensor/0.1391)-0.0329)*g;
        fsensor2 = ((vsensor/0.1298)+0.1321)*g;
        fsensor3 = ((vsensor/0.1386)+0.0316)*g;
        fsensor4 = ((vsensor/0.1537)-0.0524)*g;
        fsensor5 = ((vsensor/0.1378)+0.0922)*g;
        fsensor6 = ((vsensor/0.1083)-0.0096)*g;

        lforce = fsensor4 + fsensor5 + fsensor6;
        rforce = fsensor1 + fsensor2 + fsensor3;

        cout << lforce << " ";
        cout << rforce << " ";

        i--;    

    }

    myfile << lforce << " " << rforce << " "; // here I want to write the variables in different lines of the text file


    }

    myfile.close();


    return 0;
}

Solution

  • If you want to do this by manipulating file's cursor, you may use fseek and rewind functions. But I think it's unreasonbly difficult and much easier will be create 2 arrays and do somethig like this:

    lforce = fsensor4 + fsensor5 + fsensor6;
    lforceArray[5-i] = lforce;
    rforce = fsensor1 + fsensor2 + fsensor3;
    rforceArray[5-i] = rforce;
    

    And then just write these arrays into the file.