我们可以先读取字符串所占的行数,再乘以控制台的实际宽度
bool ReadFromConsole() { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); int bufsize; CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo(hConsole, &csbi)) { LOG(ERROR) << "Cannot determine console size."; return false; } else { // 计算 buffer 需要的字符个数 // 当前控制台的宽度乘以字符行数 bufsize = (csbi.srWindow.Right - csbi.srWindow.Left) * csbi.dwCursorPosition.Y; } WCHAR *buf = new WCHAR[bufsize]; COORD pos{0}; DWORD num_read; if (ReadConsoleOutputCharacter(hConsole, buf, bufsize, pos, &num_read) == 0) { delete[] buf; return false; } delete[] buf; return true; }