ตัวอย่างโค้ดภาษาซี สำหรับการวาดรูปสี่เหลี่ยมโดยใช้ ดอกจัน (*) และแทรกข้อความเข้าไปตรงกลางของสี่เหลี่ยม
ตัวอย่างโค้ด
/***************************************************
* Author : CS Developers
* Author URI: https://www.comscidev.com
* Facebook : https://www.facebook.com/CSDevelopers
***************************************************/
#include<stdio.h>
#include<string.h>
int main()
{
int squareSize, row, col;
int maxLength, rowInsert;
int strLen, spaceLen, mod, i, j;
char str[100];
printf(" Enter number for square size : ");
scanf("%d", &squareSize);
maxLength = ((squareSize-2) * 2)-1;
rowInsert = squareSize / 2;
printf(" Enter string for insert to square (MAX=%d Char) : ", maxLength);
scanf("%s", &str);
for(row=0; row<squareSize; row++)
{
if(row==0 || row==squareSize-1)
{
printf("\t*");
for(col=0; col<squareSize-1; col++)
{
printf(" *");
}
printf("\n");
continue;
}
printf("\t* ");
if(rowInsert == row)
{
strLen = strlen(str);
spaceLen = (maxLength - strLen) / 2;
mod = (maxLength - strLen) % 2;
for(j=0; j< spaceLen; j++){
printf(" ");
}
for(i=0; i<strLen; i++){
printf("%c", str[i]);
if(i==strLen){
printf(" ");
}
}
for(j=0; j<= spaceLen + mod; j++){
printf(" ");
}
}
else
{
for(col=0; col<squareSize-2; col++){
printf(" ");
}
}
printf("*\n");
}
return 0;
}
อธิบายเพิ่มเติม
- มีการใช้ฟังก์ชั่น strlen() เพื่อหาความยาวของข้อความ ซึ่งจะต้อง include header ที่ชื่อ string.h เข้ามาเพิ่มเติมก่อนใช้งาน
- ตัวแปร maxLength ใช้เก็บจำนวนตัวอักษรสูงสุดที่จะสามารถแสดงผลได้พอดีกับสี่เหลี่ยม
- ตัวแปร rowInsert ใช้เก็บแถวที่จะใช้เพิ่มข้อความเข้าไปในสี่เหลี่ยม
ผลลัพธ์
