std :: cout在我的keyPressed字符串中打印多余的字符,可能是因为“ \ r”,例如,如果keyPressed =“ Right arrow”,当我按下向上箭头时,它将打印“ keyPressed = Up arrowoww”,然后,当我再次按向右箭头,它将再次正常打印“ keyPressed =向右箭头”,但是如果我按除“向右箭头”以外的任何箭头键,它将在末尾打印一些不需要的多余字符

Error example

源代码:

game.cpp

#include "engine.h"
#include <iomanip>

Engine eng;

int main() {
    while (eng.isRunning) {
        eng.getInput();
        std::cout << std::setw(5);
        std::cout << "\r X = " << eng.playerX;
        std::cout << "| Y = " << eng.playerY;
        std::cout << "| KEY = " << eng.keyPressed;
        Sleep(100);
    }
    return 0;
}


引擎

#ifndef ENGINE_H
#define ENGINE_H

#include <iostream>
#include <Windows.h>
#include <string>

class Engine {
public:
    // Game
    bool isRunning = true;
    bool gettingInput = true;

    // Player
    int playerX = 1;
    int playerY = 1;
    char playerModel = 'P';

    // Test / Debug
    std::string keyPressed;

    // Functions
    char getInput() {
        // Gets arrow keys states
        while (this->gettingInput) {
            this->keyPressed = "";
            if (GetAsyncKeyState(VK_RIGHT)) {
                // Right arrow key
                this->playerX++;
                this->keyPressed = "Right arrow";
                break;
            }
            else if (GetAsyncKeyState(VK_LEFT)) {
                // Left arrow key
                this->playerX--;
                this->keyPressed = "Left arrow";
                break;
            }
            else if (GetAsyncKeyState(VK_UP)) {
                // Up arrow key
                this->playerY++;
                this->keyPressed = "Up arrow";
                break;
            }
            else if (GetAsyncKeyState(VK_DOWN)) {
                // Down arrow key
                this->playerY--;
                this->keyPressed = "Down arrow";
                break;
            }
            else if (GetAsyncKeyState(VK_END)) {
                exit(0);
            }
            Sleep(255);
        }
    }
};

#endif


最好/最简单的方法来解决这个问题?
我搜索并测试了3天,但没有找到任何东西,请帮助我。

最佳答案

由于您要覆盖前一个输出,因此当您打印较短的字符串时,仍会显示前一个输出中的多余字符。用\r替换\n以查看实际输出的内容。

您可以在键名后输出一些空格,以覆盖多余的字符并清除它们。

10-06 14:29