0
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.

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
  • @BillyONeal : I beg your pardon ? :D – Mr_and_Mrs_D May 30 '12 at 15:39
  • 1
    That's what `std::vector` is for :) With raw pointers + new it's too easy to forget to call `delete []`. But `vector` does that for you (at the cost of a single pointer to store the size -- which you probably needed anyway. That is, `std::vector input(64)` and `while (std::cin >> std::setw(64) >> input.data())` instead of the code you have up there would be better. – Billy ONeal May 30 '12 at 16:59
  • Ah - thank you very much :) - btw would it call delete on a keyboard interrupt (which is the way to exit this particular app) ? – Mr_and_Mrs_D May 30 '12 at 20:37
  • 1
    Nope. (Process teardown implicitly frees resources on most operating systems, but you don't want to rely on that) – Billy ONeal May 30 '12 at 20:58

1 Answers1

3

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thanks - what is the difference in whitespace treatment ? – Mr_and_Mrs_D May 30 '12 at 15:36
  • 1
    `operator>>` skips over initial whitespace, reads printing chars, then stops at the first whitespace. `.read()` doesn't. Try feeding `" 12 34 56"` into your `operator>>` code. – Robᵩ May 30 '12 at 15:48
  • Thanks :) - the problem with read is that it waits for 64 chars - while I want to type in one char hit enter and have a branch taken (actually I wnat to just hit enter but then the while() exits lol) - while have another branch when I paste in the 64 chars. So `setw(65)` (:sigh:) – Mr_and_Mrs_D May 30 '12 at 16:17