开发者

Tabulation problem

I have some loop:

for(int i=0; i<rolls; i++)
    {
        first = rand()%6+1;
        second开发者_高级运维 = rand()%6+1;
        cout<<'('<<first<<')';
        for(int j=0; j<first; j++)
        {
            cout<<'*';
        }
        cout<<'\t'<<'('<<second<<')';
                for(int j=0; j<second; j++)
        {
            cout<<'*';
        }
        cout<<endl;
    }

It runs great but i have some problems with my output:

CPU             Player
(2)**   (3)***
(4)**** (1)*
(6)******       (5)*****
(5)*****        (6)******
(1)*    (5)*****
(3)***  (1)*
(4)**** (2)**
(3)***  (1)*
(1)*    (5)*****
(5)*****        (4)****
(2)**   (6)******
(5)*****        (3)***

Whats wrong with this tabulations?


You're asking why it is not aligned in two neat columns?

If so that's because \t moves the caret to the next tab stop from where you are. If you're at the tab stop already - you'll move one more than what you might have expected. When you print 6 chars and then \t - you'll jump to position 8. If you print 8 chars and then \t you'll jump to position 16 (assuming tabs are every 8 positions).

That's what happens in your case.

edit

That's the answer to your question What's wrong. How to solve it - see @retrodrone's answer or the duplicate post.


\t relies on tab stops that are dependent on your environment.

Instead, you should look at the iomanip header for specifying minimum column spans. See also this answer.


The width of \t is highly dependent on your specific environment. In your case, it looks like you have a tab width of 8; that is, \t adds up to eight spaces, until the current column is divisible by 8. Since (5)***** is eight characters long, \t must move to the next tab position, and adds another 8 spaces. But (4)**** is seven characters long, so \t can get away with one space.

In short: Don't use \t, explicitly move over however many spaces you want.


Change

cout<<'\t'<<'('<<second<<')';

to

cout<< setw(16) << '(' << second << ')';

and #include <iomanip>

Printing a \t character is just liking pressing the tab key on your keyboard: it moves it to the next tab stop, not a particular tab stop.

Using std::setw you can specify a particular width.


Nothing's wrong.

Tabspaces do not automatically tabulate your content for you. They simply advance the caret to the next available tabstop.

"Next available tabstop" means the next tabstop at which there is not already a character. In the case of your console, your tabstops are set such that the first tabstop happens to fall within the expected length of your first "column" of data.

Since tabstops are always, by design, configurable by the end-user's display mechanism, they are not really appropriate for tabulating.

Use fixed whitespace instead, so that you can guarantee the layout.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜