我有一个数组,它将有数千个元素。我有一个 for 循环来打印出来,但一次只有 200 个。
要继续下一个 200,用户会得到文本"按回车键继续",我使用 cin.get((; 在那里暂停。
打印变得令人敬畏,到处都是"按回车键继续",所以我想使用回车符用一些"======="覆盖"按回车键继续"。
不幸的是,当我使用 cin.get(( 时,我的程序并没有覆盖它;首先。
有没有办法解决这个问题?
string pressEnter = "nPress Enter to continue . . .";
string lineBorders = "========================================================================================================";
for (int *ia = arrayen, i = 1; ia < arrayenEnd; ia++, i++)
{
cout << setw(10) << *ia;
if (i > 9 && i % 10 == 0) {
cout << endl;
}
if (i > 199 && i < size && i % 200 == 0) {
cout << pressEnter << 'r' << flush;
cout.flush();
cin.get();
cout << lineBorders << endl;
}
}
首先,你不应该使用 std::cin.get()
。如果键入一些字符,然后按 Enter,则每个字符将导致返回一个调用std::cin.get()
。您可以改用std::getline(std::cin, string)
来消耗整行。
车符的那一刻,光标已经在新行上,因为您按了 Enter 键。 此外,回车符通常不会清除该行,而只会移动光标。您可以使用 CSI 转义序列 [1] 来实现您想要的:首先向上移动一行e[A
,然后清除整行e[2K
。
把它们放在一起,你会得到这样的东西:
#include <iostream>
#include <string>
int main() {
while (true) {
std::cout << "anbncn";
std::cout << "Press [Enter] to continue.";
std::string line;
std::getline(std::cin, line);
std::cout << "e[Ae[2K";
}
}
在窗口上,必须首先使用 SetConsoleMode()
[2] 启用转义序列解析。从文档来看,它应该看起来像这样(未经测试,我没有窗口(:
#include <iostream>
#include <string>
#include <windows.h>
int main() {
// Get a handle to standard input.
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD old_mode;
bool escape_codes = false;
// Get the old mode and enable escape code processing if everything works.
if (handle != INVALID_HANDLE_VALUE) {
if (GetConsoleMode(handle, &old_mode)) {
DWORD new_mode = old_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
escape_codes = SetConsoleMode(handle, new_mode);
}
}
while (true) {
// Same as other platforms.
std::cout << "anbncn";
std::cout << "Press [Enter] to continue.";
std::string line;
std::getline(std::cin, line);
// Only print escape codes if we managed to enable them.
// Should result in a graceful fallback.
if (escape_codes) {
std::cout << "e[Ae[2K";
}
}
// Restore the old mode.
if (escape_codes) {
SetConsoleMode(handle, old_mode);
}
}