C++ 中的右对齐输出流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5201619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:39:26  来源:igfitidea点击:

Right Justifying output stream in C++

c++

提问by Matt Dunbar

I'm working in C++. I'm given a 10 digit string (char array) that may or may not have 3 dashes in it (making it up to 13 characters). Is there a built in way with the stream to right justify it?

我在 C++ 中工作。我得到一个 10 位字符串(字符数组),其中可能有也可能没有 3 个破折号(最多 13 个字符)。流是否有内置的方式来正确证明它?

How would I go about printing to the stream right justified? Is there a built in function/way to do this, or do I need to pad 3 spaces into the beginning of the character array?

我将如何正确地打印到流?是否有内置函数/方法来执行此操作,或者我是否需要在字符数组的开头填充 3 个空格?

I'm dealing with ostream to be specific, not sure if that matters.

我正在处理 ostream 的具体问题,不确定这是否重要。

回答by florin

You need to use std::setwin conjunction with std::right.

您需要std::setwstd::right.

#include <iostream>
#include <iomanip>

int main(void)
{
   std::cout << std::right << std::setw(13) << "foobar" << std::endl;
   return 0;
}

回答by NullUserException

Yes. You can use setw()to set the width. The default justification is right-justified, and the default padding is space, so this will add spaces to the left.

是的。您可以使用setw()来设置宽度。默认对齐是右对齐,默认填充是空格,所以这会在左边添加空格。

stream << setw(13) << yourString

See: setw(). You'll need to include <iomanip>.

见:setw()。您需要包括<iomanip>.

回答by Jollymorphic

See "setw" and "right" in your favorite C++ (iostream) reference for further details:

有关更多详细信息,请参阅您最喜欢的 C++ (iostream) 参考中的“setw”和“right”:

 cout << setw(13) << right << your_string;

回答by demonkiller

You can avoid the std:: by typing

您可以通过键入来避免 std::

using namespace std;

after the header files

在头文件之后