c/c++语言开发共享如何在C控制台中居中文本?

作为标题。 有什么方法可以做到这一点? 假设我想在屏幕中央打印“Hello World”。

    您可以使用SetConsoleCursorPosition函数。 获取控制台窗口的宽度和高度,然后调用它。

    COORD coord; coord.X = width / 2; coord.Y = height / 2; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); 

    您需要知道将字符串置于中心所需的空间有多宽; 你需要知道字符串有多长。 您编写了适当数量的空格,字符串和换行符。

     #include  int main(void) { int width = 80; char str[] = "Hello world"; int length = sizeof(str) - 1; // Discount the terminal '' int pad = (length >= width) ? 0 : (width - length) / 2; printf("%*.*s%sn", pad, pad, " ", str); return(0); } 

    详尽的测试程序(最大宽度为80):

     #include  #include  int main(void) { int width = 80; char str[81]; for (int i = 1; i <= width; i++) { memset(str, 'a', i); str[i] = ''; int length = i; int pad = (length >= width) ? 0 : (width - length) / 2; printf("%*.*s%sn", pad, pad, " ", str); } return(0); } 

    您可以使用gotoxy()函数,就像在C ++中一样,但在C中,它不是预先定义的,因此您应该首先定义它。 另一种方法是只使用制表符和换行符( t和 n …)

      以上就是c/c++开发分享如何在C控制台中居中文本?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549401.html

      (1)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐