How to use C++ std::ostream with printf-like formatting?

前端 未结 8 2006

I am learning C++. cout is an instance of std::ostream class. How can I print a formatted string with it?

I can still use printf

8条回答
  •  眼角桃花
    2020-12-05 07:25

    Field Width

    Setting field width is very simple. For each variable, simply precede it with "setw(n)". Like this:

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
      const int max = 12;
      const int width = 6;
      for(int row = 1; row <= max; row++) {
          for(int col = 1; col <= max; col++) {
              cout << setw(width) << row * col;
          }
          cout << endl;
      }
      return 0;
    }
    

    Notice how "setw(n)" controls the field width, so each number is printed inside a field that stays the same width regardless of the width of the number itself.

    -- From "Programming/C++ tutorial" by P. Lutus.

提交回复
热议问题