0

I view an example of setw on cppreference. It use setw to set the width. In this example it suppose to extract a string to 'arr', and it set width 6. But why 'arr' only have 5 characters, why the result is "hello" not "hello,"? Thank you for your answer.

code source:std::setw

  #include <sstream>
  #include <iostream>
  #include <iomanip>

  int main()
  {
      std::cout << "no setw:" << 42 << '\n'
                << "setw(6):" << std::setw(6) << 42 << '\n'
                << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
      std::istringstream is("hello, world");
      char arr[10];
      is >> std::setw(6) >> arr;
      std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
                << arr << "\"\n";
  }

Output:

  no setw:42
  setw(6):    42
  setw(6), several elements: 89    1234
  Input from "hello, world" with setw(6) gave "hello"
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • See non-member operator>> for char* argument. As cppreference puts it, it stops when "`st.width()-1` characters are extracted" – Cubbi May 07 '18 at 13:34

2 Answers2

0

arr is actually populated with 6 characters, 5 for the hello world, the 6th being the terminating NULL character. As you extract into a char array, the C++ stream receives only a char pointer (arrays decay to pointers in function calls) and assumes that setw was used to pass the size of the array. So the last position is reserved for the terminating null.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

arr is not a std::string but an array of char, thus the explanation of Serge. Would arr be a std::string, then it'll contain "hello,".