格式化目标如下
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/