如何在C代码中转到上一行

Ren*_*h G 2 c escaping

如果为以下代码:

printf("HEllo\n");    // do not change this line.
printf("\b\bworld");
Run Code Online (Sandbox Code Playgroud)

我需要一个输出:Helloworld(在一行中)。但这行不通。有人可以解释原因吗?和其他转义序列(如果有)。

Cod*_*ray 5

简单地说:

printf("Helloworld");
Run Code Online (Sandbox Code Playgroud)

\n是新行的转义序列。由于您希望所有内容都显示在同一行上,因此无需指定\n


问题是在打印新行之后,您将无法可靠地向后移动一行(使用\b)。但是,如果您需要在源代码中包含两行代码,则可以简单地省略两个转义序列:

printf("HEllo");
printf("world");
Run Code Online (Sandbox Code Playgroud)


如果要编写Win32控制台应用程序,则可以利用Console Screen Buffer API。以下代码将向上移动1行:

printf("HEllo\n");

CONSOLE_SCREEN_BUFFER_INFO coninfo;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &coninfo);
coninfo.dwCursorPosition.Y -= 1;    // move up one line
coninfo.dwCursorPosition.X += 5;    // move to the right the length of the word
SetConsoleCursorPosition(hConsole, coninfo.dwCursorPosition);

printf("world");
Run Code Online (Sandbox Code Playgroud)

输出:

你好,世界


tem*_*def 5

没有独立于平台的控制字符可向上移动一行。这可以追溯到行式打印机的时代,在那里printf实际上可以将一行文本打印到一张纸上,并且无法收回纸张以覆盖已经打印的内容。

就是说,有像ncurses这样的库,可让您在控制台上移动光标。它们只是标准库的一部分。