在 C++ 中右对齐输出

2023-11-25

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    cout << right << "Hello" << setw(10) << "World\n";
    cout << right << "Goodbye"  << setw(10) << "World\n";
}

为什么这会导致输出如下:

Hello    World
Goodbye    World

而不是:

Hello    World
Goodbye  World

我在这里做错了什么?

EDIT:

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    cout    << "Hello"  <<  " World";
    cout << right << setw(10) << "today\n";
    cout   << "Goodbye"  <<  " World";
    cout << right << setw(10) << "today\n";
}

如果我尝试这样做,为什么“今天”部分未对齐?


改变运算符的顺序来解决这个问题:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::left << std::setw(10) << "Hello" << "World\n";
    std::cout << std::left << std::setw(10) << "Goodbye" << "World\n";
    return 0;
}
  • 您必须放置所有运算符before您想要格式化的值。
  • 避免使用using namespace std.

The std::setw()运算符将字段设置为下一个值。还有std::left or std::right运算符设置该字段中值的位置。

这个例子

std::cout << std::left << std::setw(10) << "word1"
    << std::right << std::setw(20) << "word2" << std::endl;

将创建这种格式:

AAAAAAAAAABBBBBBBBBBBBBBBBBBBB
word1                    word2

您会看到第一个“字段”包含 10 个字符,其中放置第一个文本,第二个“字段”包含 20 个字符,其中第二个单词右对齐放置。但如果第一个字段中的文本比该字段长,则会发生这种情况:

AAAAAAAAAA....BBBBBBBBBBBBBBBBBBBB
word1istoolong               word2

第二个字段只是移动了字符数。流永远不会跟踪当前位置,它只是使用给定大小的“字段”构建输出。

要对齐给定页面的文本,请使用如下代码:

#include <iostream>
#include <sstream>
#include <list>

const int pageWidth = 78;
typedef std::list<std::string> WordList;

WordList splitTextIntoWords( const std::string &text )
{
    WordList words;
    std::istringstream in(text);
    std::string word;
    while (in) {
        in >> word;
        words.push_back(word);
    }
    return words;
}

void justifyLine( std::string line )
{
    size_t pos = line.find_first_of(' ');
    if (pos != std::string::npos) {
        while (line.size() < pageWidth) {
            pos = line.find_first_not_of(' ', pos);
            line.insert(pos, " ");
            pos = line.find_first_of(' ', pos+1);
            if (pos == std::string::npos) {
                pos = line.find_first_of(' ');
            }
        }
    }
    std::cout << line << std::endl;
}

void justifyText( const std::string &text )
{
    WordList words = splitTextIntoWords(text);

    std::string line;
    for (WordList::const_iterator it = words.begin(); it != words.end(); ++it) {
        if (line.size() + it->size() + 1 > pageWidth) { // next word doesn't fit into the line.
            justifyLine(line);
            line.clear();
            line = *it;
        } else {
            if (!line.empty()) {
                line.append(" ");
            }
            line.append(*it);
        }
    }
    std::cout << line << std::endl;
}

int main()
{
    justifyText("This small code sample will format a paragraph which "
        "is passed to the justify text function to fill the "
        "selected page with and insert breaks where necessary. "
        "It is working like the justify formatting in text "
        "processors.");
    return 0;
}

此示例将每一行对齐以在开头填充给定页面。它的工作原理是将文本分割成单词,用这些单词填充行,并使每行对齐以完全匹配宽度。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++ 中右对齐输出 的相关文章

随机推荐

  • Emacs/CEDET。多个项目和代码完成

    我已经使用 CEDET 1 0 和 ECB 2 40 设置了 emacs 23 1 50 1 很大程度上受到 Alex Otts 设置的启发 http github com alexott emacs configs blob master
  • CSS:-webkit-mask-image

    我正在使用 CSS 属性 webkit mask image 在图像上应用蒙版 但是 在 Chrome 中 当您将图像滚动到页面之外时 遮罩会移动 如何防止面罩移动 还是渲染神器 JSFiddle http jsfiddle net DZT
  • Scala 中不明确的导入

    我正在用 Scala 编写一个小型模拟程序 它是基于演员的 所以我创建了一个文件messages scala包含系统中所有有效的消息 除此之外 我还有一个管理组件 management scala以及定义节点和链接类的文件nodes sca
  • 在 GCP Cloud Run/Function 上使用固定公共 IP(列入白名单)

    我正在寻找将应用部署到 GCP 的最佳方法 该应用程序需要使用微服务 在Cloud Run或Cloud Function上运行 在远程数据库上执行SQL代码 基本上 微服务接收一段 SQL 代码 并需要在远程数据库上执行它 出于安全原因 远
  • 给 CSS 样式的 div 一个“border-left-image”

    只是想给网站上的主要内容 div 的左侧和右侧添加边框 我不想为每个边框设置单独的 div 而是使用border left imageCSS3 中的功能可以实现这一目标 我的代码如下 content background color 7FC
  • 将 Roslyn 编译器与 Visual Studio 2013 结合使用

    有没有办法将 Roslyn 编译器与 Visual Studio 2013 一起使用 以便我可以利用新的 C 6 功能 注意 不能使用 VS 2015 Yes 您可以使用 Visual Studio 2013 编译 C 6 代码 您只需安装
  • 斐波那契递归函数如何“工作”?

    当我读到描述函数递归的一章时 我是 Javascript 的新手 正在阅读它 它使用示例函数来查找斐波那契数列的第 n 个数字 代码如下 function fibonacci n if n lt 2 return 1 else return
  • 考虑添加 android:paddingStart="25dp" 以更好地支持从右到左布局错误

    我最近下载了一个新的ADT 每次保存我的项目后 它都会显示以下内容XML错误 但当我清理它时 同样的情况就会消失 有没有永久的解决方案 提前致谢
  • Ruby:从块中产生块?

    是否有可能lambda proc method或红宝石中其他类型的块 以屈服于另一个块 就像是 a lambda puts in a yield if block given a call puts in a s block 这不起作用 它
  • 每个块的 CUDA 线程限制

    为什么我不能使用 max ofMax dimension size of a thread block x y z 1024 1024 64 如果我使用 1024 1024 它不起作用 当我使用时 32 32 or 1 1024 等等它有效
  • Android FirebaseAuth.getCurrentUser() 从不为空

    我有一个 DispatchActivity 作为我的 Launcher Activity 其目的是检查当前是否有用户登录 如果用户已登录 我会将其发送到他们的 ProfileActivity 否则 我将它们发送到 LogInActivity
  • 动态查询 sqlalchemy 中的列子集

    假设表中只需要两列 名称和 ID 我会编写如下代码 session query User id User name all 但如果列名是动态的 def get data table columns return session query
  • C++:数组的构造函数初始化列表?

    我有一个基本问题 我有一个带有数据成员的类 double mydata N N 是模板参数 使用构造函数初始化列表将这些数据初始化为零的语法是什么 是 mydata 0 根据 C 标准 对于所有编译器也是如此 可以吗 非常感谢 不 在 C
  • 类加载器如何加载清单类路径中的类引用?

    我使用 Maven 构建了一个带有外部类路径添加的 jar添加类路径 当我使用运行该罐子时java jar artifact jar它能够从该主 jar 和 libs 目录中的所有 jar 加载类 但是如果我询问系统属性java class
  • 在会话中发出后续 POST 请求不起作用 - 网络抓取

    这就是我想做的 去here 然后点击 搜索 获取数据 然后点击 下一步 并继续点击下一步 直到页面用完 直到点击 下一步 为止的一切都有效 这是我的代码 r content 的格式在我打印两次时完全不同 这表明 GET 和 POST 请求之
  • DataGridView 中的超链接

    我正在开发 C 应用程序 它就像一个小型搜索引擎 用户输入一个单词 程序将返回包含该单词的文件 我有一个文件路径数组 作为字符串 我想将这些路径显示为DataGridView 以便当用户单击文件名时将打开该文件 注意 我正在使用 C Win
  • PHP HTTP 引荐来源网址

    我有一个接受来自远程站点的 POST 的页面 我想检测这些帖子来自的域 我意识到它可以被欺骗 但总比没有好 我尝试访问 HTTP REFERER 变量 但它只返回 null 该页面接受来自 PayPal 即时付款通知 和其他支付网关等来源的
  • 如何在 Xamarin Forms 中集成 Apple Pay?

    我正在使用 xamarin Forms 开发应用程序 现在 我需要集成 Apple Pay 我试图通过互联网查找内容 但无法找到有效的解决方案 谁能建议我如何将 Apple pay 集成到我的应用程序中 这是我的 Apple pay 代码
  • 如何在不更改部署服务器上的区域设置的情况下导入平面文件?

    我正在尝试读取 SSIS 2005 2008 中的文本文件 我创建了到该文件的连接并放置了平面文件源 它在预览中工作正常 但当我尝试运行时出现错误 Derived Column 91848 Error SSIS Error Code DTS
  • 在 C++ 中右对齐输出

    include