如何在一行中输出一个变量的所有值,在另一行输出另一个变量的所有值?

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

我有这个程序 (c++) 在 while 循环中计算两个变量值。我正在尝试将这些值写入文本文件。现在我想在文本文件的一行中写入 lforce 变量的 5 个值,在另一行中写入 rforce 变量的 5 个值线。 我该怎么做?

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

如果你想通过操作文件的光标来做到这一点,你可以使用 fseek and rewind 函数。但我认为这非常困难,创建 2 个数组并执行如下操作要容易得多:

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

然后将这些数组写入文件即可。