C语言怎么实现将输入的字符居中显示?

2025-03-23 19:46:47
推荐回答(5个)
回答1:

给你一个函数,随意控制输入输出的位置,可以先打印下一行,再在上一行输入。

void setxy(int x, int y)  //设置输入,输出的位置,也就是当前光标位置
{
   COORD coord = {x, y};
   SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void getxy(int* x, int* y) //获取当前光标位置,调用:getxy(&x,&y);

{                          
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coordScreen = {0, 0};
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    if (GetConsoleScreenBufferInfo(hConsole, &csbi))
    {
        *x=csbi.dwCursorPosition.X;
        *y=csbi.dwCursorPosition.Y;
    }
}
//要加头文件 #include "windows.h"

 

回答2:

#include

#include

int main() 

{

char s[80];

int a;

gets(s);

a=strlen(s);

printf("%*c%s\n",(80-a)/2,' ',s);

getch();

}

回答3:

/**
 *c语言练习程序
 *时间:2016/1/10
 *环境:vs2013
 */
#include 
#include 
#include 
#include 
int main(void){
//利用printf右对齐
//让这个输出占用控制台宽度值的一半减去字符串一半长度的内容
//控制台宽度可以右键左上角,属性查看,默认是80所以下面的50改为40
//我的是100,因为我自己改过
//你可打印一下s1,就明白我的想法了
    char s[] = "hell0000000000000000000000000000!";
    char s1[10]; 
    sprintf_s(s1,"%%%ds",50+(int)strlen(s)/2);
    printf(s1, s);
    getchar();
    return 0;
}
//原来是输入啊,换个tc写,包含conio.h,里面有个gotoxy()。其他没办法了

回答4:

C语言对格式输出支持不是很好,因为一般C语言不会做太复杂的显示 ,最多也就打印一些调试信息, 你可以printf 格式输出符来试试
如: printf("%-100s\n", "adfdfadgda"); 可以百度一下

回答5:

按以下代码的思路就能实现:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
int main(void){
    char str[20];
    printf("%55s","Please input a string: ");
    scanf("%s",str);
    printf("%53s\n",str);
    return 0;
}