在cin之前打印"cout"?

Print "cout" before cin?

我遇到了一个小问题,我不确定是否可以使用 iostream 代码解决这个问题,但我认为无论如何都值得一问。

#include <iostream>
#include <string>

using namespace std;

string cmd;

int main() {

cout << "-------------" << endl;
cout << "command: ";
cin >> cmd;
cout << "-------------" << endl;
system("pause");
}

是否可以在用户输入 cmd 变量之前打印第 3 cout 行?这样,文本字段将被上下包裹 "-",如下所示:

-------------
command: <user would type here>
-------------

如果这不可能,能否请您指出一些我可以用来实现此目标的可能库的方向?

在 C++ 中没有实现此目的的标准方法。

不同的终端有自己的能力,不同的系统有自己的API与终端交互。

底部行的输出当然必须在等待输入之前先执行,但是可以将输出"cursor"移动到屏幕底部以外的其他位置。您可以在您打算定位的系统的文档中找到详细信息。

我建议您可以尝试使用 SetConsoleCursorPosition function 在指定的控制台屏幕缓冲区中设置光标位置。

此代码使用 SetConsoleCursorPosition() 将当前输出位置移动到第 1 行第 9 列:

#include <iostream>
#include <string>

#include <windows.h>

using namespace std;

string cmd;

int main()
{


    cout << "-------------\n" << "command:  \n" << "-------------" << endl;


    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    if (INVALID_HANDLE_VALUE != hConsole)
    {
        COORD pos = {9, 1 };
        SetConsoleCursorPosition(hConsole, pos);
        cin >> cmd;
    }


    system("pause");

}