c/c++的一道练习题: 使用纯c函数完成打印一组数字,如输入314,输出:
******* * *
* * * *
******* * *********
* * *
****** * *
/**
* 打印一串数字,如输入314,输出:
* ***** * *
* * * * * *
* ***** * ******
* * * *
* ***** ***** *
*
* 要求:使用纯c API 完成该功能
*/
#include <stdio.h>
#include <string.h>
#if defined(_MSC_VER)
#include <process.h>
#endif
#include <conio.h>
// #define nElem(array) ( sizeof(array)/sizeof(array[0]) )
typedef char* String;
static const String CHAR_DIGIT[][10] =
{
{ " ***** "," * ", " ***** ", " ***** ", " * ", " ***** ", " ***** ", " ***** ", " ***** ", " ***** " },
{ " * * "," * * ", " * ", " * ", " * * ", " * ", " * ", " * * ", " * * ", " * * " },
{ " * * "," * ", " ***** ", " ***** ", " ****** ", " ***** ", " ***** ", " * ", " ***** ", " ***** " },
{ " * * "," * ", " * ", " * ", " * ", " * ", " * * ", " * ", " * * ", " * " },
{ " ***** "," ***** ", " ***** ", " ***** ", " * ", " ***** ", " ***** ", " * ", " ***** ", " ***** " },
};
enum Status
{
s_ok,
s_err,
};
Status Digit2String(int dig, String*ca )
{
const size_t row = sizeof(CHAR_DIGIT)/sizeof(CHAR_DIGIT[10]);
if ( dig>=0 && dig <= 9 )
{
for (size_t i = 0; i != row; ++i )
{
memcpy(ca[i], CHAR_DIGIT[i][dig], sizeof(char)*(strlen(CHAR_DIGIT[i][dig])+1) );
}
return s_ok;
}
return s_err;
}
int main(int argc, char* argv[])
{
const int bit = 5;
char dig[bit];
memset(dig, 0, sizeof(dig)); // init 0 for array "dig"
printf( "请输入%d位数字:\t", bit);
int cnt = 0;
char ch;
while((ch=getch()) != 13)
{
printf("%c", ch);
if (cnt >= bit )
{
printf( "\n不能超过%d位数字!\n", bit );
getch();
#if defined(_MSC_VER)
system("cls");
#endif
printf( "请输入%d位数字:\t", bit );
cnt = 0;
memset(dig, 0, sizeof(dig));
continue;
}
if ( 0 > (ch-'0') || (ch-'0') > 9 )
{
printf("\n输入不合法,请输入数字!\n");
getch();
#if defined(_MSC_VER)
system("cls");
#endif
printf( "请输入%d位数字:\t", bit );
cnt = 0;
memset(dig, 0, sizeof(dig));
continue;
}
dig[cnt++] = ch;
}
printf("\n");
const size_t len = strlen(dig);
const size_t row = sizeof(CHAR_DIGIT)/sizeof(CHAR_DIGIT[10]);
char cdig[row][bit][10];
memset(cdig, 0, sizeof(cdig)); // init 0 for array "cdig"
for ( size_t i = 0; i != len; ++i )
{
char *p[row];
for ( size_t j = 0; j != row; ++j )
{
p[j] = cdig[j][i];
}
Digit2String(dig[i]-'0', p);
}
//输出数字字符串
for (int i = 0; i < row; ++i )
{
for (int j = 0; j < bit; ++j )
{
printf("%s", cdig[i][j]);
}
printf("\n");
}
#if defined(_MSC_VER)
system("pause");
#endif
return 0;
}