无法在 C++ 中设置控制台 window 标题
Trouble setting console window title in C++
我一直在尝试学习如何使用 Windows API 制作 C++ 应用程序。我尝试使用一个简单的函数 SetConsoleTitle()
来设置控制台的标题 window。这是我的程序:
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main(){
TCHAR abc[5];
abc[0] = 'H';
abc[1] = 'E';
abc[2] = 'L';
abc[3] = 'L';
abc[4] = 'O';
SetConsoleTitle(abc);
std::cout << "Hello World\n";
system("pause > nul");
}
这是结果
标题本来应该是 "HELLO"
。其他角色在那里做什么,我该如何摆脱它们?
我使用 Visual studio Code 2019 编译了这段代码。
正如@AlanBirtles 所说,您需要以 null 终止字符串。这是 C++ 知道字符串有多长的唯一方法。可以通过三种方式做到这一点:
TCHAR abc[6]; // <-- increase this size
...
abc[5] = '[=10=]'; // <-- add this
TCHAR abc[] = "HELLO"; // the terminator will be added automatically
TCHAR abc[6] = {0}; // the string will consist of all nulls and you can then overwrite just the first 5
我一直在尝试学习如何使用 Windows API 制作 C++ 应用程序。我尝试使用一个简单的函数 SetConsoleTitle()
来设置控制台的标题 window。这是我的程序:
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main(){
TCHAR abc[5];
abc[0] = 'H';
abc[1] = 'E';
abc[2] = 'L';
abc[3] = 'L';
abc[4] = 'O';
SetConsoleTitle(abc);
std::cout << "Hello World\n";
system("pause > nul");
}
这是结果
标题本来应该是 "HELLO"
。其他角色在那里做什么,我该如何摆脱它们?
我使用 Visual studio Code 2019 编译了这段代码。
正如@AlanBirtles 所说,您需要以 null 终止字符串。这是 C++ 知道字符串有多长的唯一方法。可以通过三种方式做到这一点:
TCHAR abc[6]; // <-- increase this size
...
abc[5] = '[=10=]'; // <-- add this
TCHAR abc[] = "HELLO"; // the terminator will be added automatically
TCHAR abc[6] = {0}; // the string will consist of all nulls and you can then overwrite just the first 5