更新同一行上的printf值而不是新行

Yam*_*088 12 c

我想知道是否有办法C覆盖已经打印的现有值,而不是每次都创建一个新行或只是移动一个空格.我需要从传感器获取实时数据,并希望它只是坐在那里并不断更新现有值而无需任何滚动.这可能吗?

更新:增加的代码

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#include <wiringPi.h>
#include <wiringPiI2C.h>

#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23


int fd;
short x = 0;
short y = 0;
short z = 0;
int main (){



    fd = wiringPiI2CSetup(0x69); // I2C address of gyro
    wiringPiI2CWriteReg8(fd, CTRL_REG1, 0x1F); //Turn on all axes, disable power down
    wiringPiI2CWriteReg8(fd, CTRL_REG3, 0x08); //Enable control ready signal
    wiringPiI2CWriteReg8(fd, CTRL_REG4, 0x80); // Set scale (500 deg/sec)
    delay(200);                    // Wait to synchronize

void getGyroValues (){
    int MSB, LSB;

    LSB = wiringPiI2CReadReg8(fd, 0x28);
    MSB = wiringPiI2CReadReg8(fd, 0x29);
    x = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg8(fd, 0x2B);
    LSB = wiringPiI2CReadReg8(fd, 0x2A);
    y = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg8(fd, 0x2D);
    LSB = wiringPiI2CReadReg8(fd, 0x2C);
    z = ((MSB << 8) | LSB);
}
    for (int i=0;i<10;i++){
    getGyroValues();
    // In following Divinding by 114 reduces noise
    printf("Value of X is: %d\r", x/114);
//  printf("Value of Y is: %d", y/114);
//  printf("Value of Z is: %d\r", z/114);
    int t = wiringPiI2CReadReg8(fd, 0x26);
    t = (t*1.8)+32;//convert Celcius to Fareinheit
    int a = wiringPiI2CReadReg8(fd,0x2B);
    int b = wiringPiI2CReadReg8(fd,0x2A);
//  printf("Y_L equals: %d\r", a);
//  printf("Y_H equals: %d\r", b);
    int c = wiringPiI2CReadReg8(fd,0x28);
    int d = wiringPiI2CReadReg8(fd,0x29);
//  printf("X_L equals: %d\r", c);
//  printf("X_H equals: %d\r", d);
    int e = wiringPiI2CReadReg8(fd,0x2C);
    int f = wiringPiI2CReadReg8(fd,0x2D);
//  printf("Z_L equals: %d\r", e);
//  printf("Z_H equals: %d\r", f); 

//  printf("The temperature is: %d\r", t); 
    delay(2000);
}
};
Run Code Online (Sandbox Code Playgroud)

Yan*_*niv 23

你正在寻找回车.在C中,那是\r.这会将光标移回当前行的开头而不开始新行(换行)

  • 一个有趣的问题是要打印的新行是否比先前打印的行短。在这种情况下,屏幕上也会显示前一行的某些部分。 (2认同)

Zax*_*ter 20

您应该\r像其他人所说的那样添加到您的printf中.此外,请确保刷新stdout,因为stdout流被缓冲并且只会在到达换行符后显示缓冲区中的内容.

在你的情况下:

for (int i=0;i<10;i++){
    //...
    printf("\rValue of X is: %d", x/114);
    fflush(stdout);
    //...
}
Run Code Online (Sandbox Code Playgroud)

  • `fflush`是一个关键注释,因为在大多数平台上它没有这个功能. (4认同)

Gor*_*bag 5

您可以使用"\ r"而不是"\n"来完成此操作.