如何使用cout将文本向右对齐? [英] How to Align text to the right using cout?

查看:802
本文介绍了如何使用cout将文本向右对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串s,如下所示:

Suppose I have a string s which is given below:

string s="i am\ngoing\nto\ncuet";

在控制台中显示期间,我想将字符串右对齐.所以我想显示这样的输出:

I want to align the string to the right during display in console. So I want to show output like this:

编辑:最右边的字符应对齐.

rightmost characters should be aligned.

                                      i am
                                     going
                                        to
                                      cuet

我尝试了以下代码以显示输出:

I tried this code to show the output:

cout.width(75);
cout<<s;

但是它只能像这样将第一行右对齐:

But it only right align the first line like this:

                                                         i am
going
to
cuet

然后我尝试使用此代码来获取输出:

Then I tried this code to get the output:

for(int i=0 ; i<s.size(); i++)
    {
        cout.width(75);
        cout<<s[i];
    }

但是我使用以下代码得到了奇特的输出:

But I get peculiar output using this code:

                                                                  i

                                                        a
                                                   m

                                                                  g
                                                             o
                                                        i
                                                   n
                                              g

                                                                  t
                                                             o

                                                                  c
                                                             u
                                                        e
                                                   t

如何获得所需的输出?

推荐答案

您需要逐行阅读s,然后将每行右对齐输出.

You need to read s line by line, then output each line right aligned.

#include <iostream>
#include <iomanip>
#include <sstream>

void printRightAlignedLines(const std::string& s, int width)
{
    std::istringstream iss(s); //Create an input string stream from s
    for (std::string line; std::getline(iss, line); ) //then use it like cin
        std::cout << std::setw(width) << line << '\n';
}

int main()
{
    std::string s = "i am\ngoing\nto\ncuet";
    printRightAlignedLines(s, 75);
}

这篇关于如何使用cout将文本向右对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆