【发布时间】:2018-12-21 21:04:45
【问题描述】:
std::cout 在我的 keyPressed 字符串中打印额外的字符,可能是因为“\r”,例如,如果 keyPressed = “右箭头”,当我按下向上箭头时,它会打印“keyPressed = Up arrowoww”,然后,当我再次按右箭头时,它会再次正常打印“keyPressed = 右箭头”,但如果我按“右箭头”以外的任何箭头键,它会在最后打印一些不需要的额外字符
源码:
游戏.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;
}
engine.h
#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天,但没有找到任何东西,请帮助我。
【问题讨论】:
标签: c++ windows command-line c++17 cout