c++ - 如何使用cout将文本右对齐?

标签 c++ string output cout right-align

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

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

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

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

                                      i am
                                     going
                                        to
                                      cuet

我尝试使用此代码来显示输出:

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

但它只能右对齐第一行,如下所示:

                                                         i am
going
to
cuet

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

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

但是我使用这段代码得到了特殊的输出:

                                                                  i

                                                        a
                                                   m

                                                                  g
                                                             o
                                                        i
                                                   n
                                              g

                                                                  t
                                                             o

                                                                  c
                                                             u
                                                        e
                                                   t

如何获得所需的输出?

最佳答案

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

#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);
}

关于c++ - 如何使用cout将文本右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43033802/

相关文章:

C++ 命名空间、类名和命名空间::类名冲突时怎么办

c++ - 从一个类中实例化的对象调用另一个类中的函数

python - 用条纹数替换字符串

c - 用 C 编写的蛇视频游戏 map

java - Javasound Mixer不显示任何输出设备

c++ - 尝试使用指针反转字符串

c++ - 检查来自不同类的两个 Rect 之间的碰撞

objective-c - 从 NSString 中删除前缀

c++ - 需要用户输入字符串/检查字符串长度(C++)

python - 如何找出 python 函数返回的输出数量?