我有一个包含数千个元素的数组。我有一个 for 循环来打印它,但一次只能打印 200 个。
要继续下一个 200,用户会收到文本“按回车键继续”,我使用 cin.get();就在那儿暂停。
到处都是“Press Enter to continue”,打印变得很糟糕,所以我想用回车来用一些“======”覆盖“Press Enter to Continue”。
不幸的是,当我使用 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 << "a\nb\nc\n";
std::cout << "Press [Enter] to continue.";
std::string line;
std::getline(std::cin, line);
std::cout << "\e[A\e[2K";
}
}
在 Windows 上,您必须首先使用 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 << "a\nb\nc\n";
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[A\e[2K";
}
}
// Restore the old mode.
if (escape_codes) {
SetConsoleMode(handle, old_mode);
}
}
关于c++ - cin.get() 后的回车; C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451451/