c++ - 显示字符串结尾字符的控制台
问题描述
我只是在搞乱 CPP 和 Windows 控制台。我需要更改我拥有的屏幕缓冲区的特定部分,但它总是打印我想要的字符串加上一个空的方框。
有没有办法去掉这个空白框?
int screen_w = 120;
int screen_h = 30;
void init_screen(wchar_t* screen_buffer, int screen_w, int screen_h) {
for (int i = 0; i < screen_h; ++i) {
for (int j = 0; j < screen_w; ++j) {
if (i != 0 && i != 2 && i != screen_h - 1 &&
j != 0 && j != screen_w - 1) {
screen_buffer[i * screen_w + j] = ' ';
} else {
screen_buffer[i * screen_w + j] = '#';
}
}
}
}
int main() {
int screen_s = screen_w * screen_h;
wchar_t *screen_buffer = 0;
screen_buffer = (wchar_t *) calloc(screen_s, sizeof *screen_buffer);
HANDLE c_handle = CreateConsoleScreenBuffer(
GENERIC_WRITE | GENERIC_READ,
0,
0,
CONSOLE_TEXTMODE_BUFFER,
0);
SetConsoleActiveScreenBuffer(c_handle);
DWORD bytes_written = 0;
init_screen(screen_buffer, screen_w, screen_h);
while (1) {
Sleep(1000 / 10);
WriteConsoleOutputCharacterW(c_handle, screen_buffer, screen_s, { 0, 0 }, &bytes_written);
wsprintfW(&screen_buffer[15 * screen_w + 60], L"hello world"); // THIS IS WHAT I DO.
// TRIED OTHER SIMILAR FUNCTIONS.
if (GetAsyncKeyState(VK_SPACE) & 0x8000) break;
}
free(screen_buffer = 0);
return 0;
}
它显示了什么:
########################################################################################################################
# #
########################################################################################################################
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# hello world▯ #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
########################################################################################################################```
解决方案
问题是您的wsprintfW()
调用(或任何函数系列)会将(必需的)终止符sprintf
附加到输出缓冲区段......这可能会在某些平台的控制台中呈现为“奇怪”字符。nul
因此,与其尝试将格式化的字符串写入缓冲区,不如使用直接内存复制例程。
以下行 - 代替您的wsprintf(...)
电话 - 将起到作用:
memcpy(&screen_buffer[15 * screen_w + 60], L"hello world", wcslen(L"hello world") * sizeof(wchar_t));
但是您可以使用声明的(本地)变量使代码看起来更漂亮/更简单:
const wchar_t* text = L"hello world";
memcpy(&screen_buffer[15 * screen_w + 60], text, wcslen(text) * sizeof(wchar_t));
推荐阅读
- apache - Gemfire 在启动定位器时抛出 502 Gateway 错误
- javascript - 如果我多次运行初始化,为什么我的 jquery onclick 函数会打开和关闭?
- c# - 与 Specflow 并行运行 BDD 测试时,如何在 C# 中创建范围报告
- c++ - 这是使用 VariantCopy() 的正确方法吗
- python - 在 jupyter-lab 中显示来自数组的视频的快速方法
- mysql - MySQL JSON:如何检查数组中的对象是否具有给定第一个键值的两个键
- android - 如何使用内容值通过外键将数据插入 SQLITE 数据库?
- java - 使用 thread.join() 时抛出 NullPointerException
- python-3.x - 带有 Numpy 数组的矢量化累积串联
- nrwl - 如何在 Nrwl NX 工作区中使用 CSS 模块?