Question

input = new char[64]();
std::cout << "wait for cin" << std::endl;
while (std::cin >> std::setw(64) >> input)
{
    std::cout << "input : " << input << std::endl;
    ...

Well I assure you setw() copies 63 characters to the char * input instead of 64 and I see the 64rth character displayed on the next while(cin) iteration. Can this behavior be overridden ? I want all my 64 chars and NO nul in my array.

Was it helpful?

Solution

operator>>(istraem&, char*) will always write the nul byte.

C++2003, 27.6.1.2.3/7 (emphasis added):

Characters are extracted and stored until any of the following occurs:

  • n-1 characters are stored;
  • end of file occurs on the input sequence;
  • ct.is(ct.space,c) is true for the next available input character c, where ct is use_facet >(in.getloc()).

Operator>> then stores a null byte (charT()) in the next position, which may be the first position if no characters were extracted. operator>> then calls width(0).

You can get nearly the behavior you want

  • allocate a 65-byte array and call setw(65), or
  • call std::cin.read(input, 64).

Note that the two solutions are not identical. Using std::cin >> input treats whitespace differently than std::cin.read() does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top