Why does not the string affect the char array?


I'm trying to insert the contents of a std::string to a char array. So I make a stringstream and do getline on it but for some reason the last character is missing from the array a when I print it. Why is this?

#include <iostream>
#include <sstream>
#include <string>

int main()
   std::string str = "Hello, World";
   std::stringstream ss(str);

   char a[256];

   ss.getline(&a[0], str.length());

   std::cout << a; // "Hello, Worl"

The reason is because the second argument of getline is supposed to give the size of the buffer you are willing to give up and not the number of characters to extract. So in fact, the size includes the null character. You are saying that you want it to extract 12 characters (the length of the string) at most. Since we need to make room for the null character, of course we can only fit in one less than the whole string.

Really, you're supposed to use it like this:

ss.getline(a, 256);

The argument is the maximum number of chars it will possibly write to in the array, not the number of characters from the string you want to take. The number of characters it extracts is determined by the delimeter (which is \n in this case). You can, of course, make 256 whatever number of chars from a you want to allow it to write to. Just remember that it includes the null character.

Note that &a[0] is unnecessary. Arrays will undergo array-to-pointer conversion if need be.