开发者

How can I print a blank char using printf?

I'm currently using the following code to print the elapsed time (in seconds) on the screen:

for(int i = 1;  i < 20;  i++)
{
    char cheese[0];

    if(i < 10)
    {
        cheese[0] = '0';
    }
    else    cheese[0] = '\0';

    system("CLS");
    printf("%c%i", cheese[0], i);

    Sleep(1000);
}

I would like to o开发者_Go百科utput the time as:

..
08
09
10
..

How can I do that?


Use something like:

printf("%02i", i);

This will always produce at least two digits, with leading zeros if necessary.

If you wanted to pad with a space instead of zero, you should use:

printf("%2i", i);

Would produce:

 1
 2
10

Not recommended:

If you wanted to do that without using the size specifier in the format string, you could do a trick like this:

char pad[2];
pad[1] = 0; // make sure the pad string is terminated properly
if (i >= 10) {
 pad[0] = 0; // plain zero - end of string marker
} else {
 pad[0] = '0'; // character zero
}
printf("%s%i", pad, i);

pad would be a zero-length string if i has at least two digits, so printf would not output a character.


for(int i = 1;  i < 20;  i++)
{
    system("CLS");
    printf("%02d", i);

    Sleep(1000);
}

... is probably closer to what you want.


If you want contant double digits, why not simply like this?

printf("%02d", i)

adding in a zero character for values >10 sound scary btw. (also because %c will print -something-, indeed the zero, unlike %s it won't stop on the first \0 encountered).


This will give the output you want

for(int i = 1;  i < 20;  i++)
{        
    printf("%d2", i);    
    Sleep(1000);
}

But if you want to print out the time elapsed you should not do it this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜