迷路的龙猫

Hacking the interesting world!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在书中看到一段代码,使用到了std::setw()这个方法,记录一下用法。

 

这个方法用来设定输入或者输出流中的缓冲区的宽度(set field width).这个方法定义在头文件<iomanip>中。

可用来对齐输出的文本流或者截取部分数据。

 

示例1:

参考自cplusplus

www.cplusplus.com/reference/iomanip/setw/

// setw example
#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw

int main () {
  std::cout << std::setw(10);
  std::cout << 77 << std::endl;
  return 0;
}
View Code

输出:

77

  

示例2:

参考自cppreference

http://en.cppreference.com/w/cpp/io/manip/setw

 1 #include <sstream>
 2 #include <iostream>
 3 #include <iomanip>
 4  
 5 int main()
 6 {
 7     std::cout << "no setw:" << 42 << '\n'
 8               << "setw(6):" << std::setw(6) << 42 << '\n'
 9               << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
10     std::istringstream is("hello, world");
11     char arr[10];
12     is >> std::setw(6) >> arr;
13     std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
14               << arr << "\"\n";
15 }
View Code

输出:

no setw:42
setw(6):    42
setw(6), several elements: 89    1234
Input from "hello, world" with setw(6) gave "hello"

 

以上

posted on 2014-03-02 20:18  迷路的龙猫  阅读(3012)  评论(0编辑  收藏  举报