C++ 如何格式化包含可变整数的文本行,使其在给定宽度内右对齐?

标签 c++ formatting iomanip

格式化目标如下

   Absolute value of the number you entered : 723
                 Square root of that number : 26.89
       Rounding this to the nearest integer : 27
  Two random numbers between 27 and 723 are : ...

这是我的代码

  cout << right << setw(50) << "Absolute value of the number you entered : " << absoluteValue << endl;
  cout << right << setw(50) << "Square root of that number : " << squareRoot << endl;
  cout << right << setw(50) << "Rounding this to the nearest integer : " << roundedSquareRoot << endl;
  cout << right << setw(50) << "Two random numbers between " << roundedSquareRoot << " and " << absoluteValue << " are : ";

当我运行时我得到这个

   Absolute value of the number you entered : 723
                 Square root of that number : 26.89
       Rounding this to the nearest integer : 27
                   Two random numbers between 27 and 723 are :

最下面一行右对齐和 setw() 仅适用于第一个“文本” 我如何使它适用于该行上的所有内容? 谢谢

编辑:明确地说,我只想让底线像前三条线一样。

最佳答案

您需要将最后一行呈现为单个字符串。
最好的选择是预先构建该字符串。

std::sstream  lastLineStream;
lastLineStream << "Two random numbers between " 
               << roundedSquareRoot << " and " 
               << absoluteValue << " are : ";

现在您可以将其打印为单个字符串。

 cout << right << setw(50) << "Rounding this to the nearest integer : " << roundedSquareRoot << endl;
 cout << right << setw(50) << lastLineStream.str();

注意:

优先选择'\n' 而不是std::endl。 它们都做同样的事情,然后 std::endl 将刷新缓冲区。手动刷新缓冲区通常是错误的做法。

关于C++ 如何格式化包含可变整数的文本行,使其在给定宽度内右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981141/

相关文章:

从文件到 8 位字符到文件的 C++ 32 位整数-程序在某个整数处崩溃

c++ - 如何避免使用特征类违反 ODR

C++ cout 对齐输出数字

java - 如何从 Java 中的输入文本中删除标点符号?

c++ - 设置整数的位数

c++ - 分离类成员声明和初始化的正确方法

c++ - 忽略 "cin"并使用 "kbhit"转到另一个函数

java - BigDecimal 的 DecimalFormat 模式。

c++ - 有没有一种组合流操纵器的好方法?

c++ - C++ 中的有效数字