Me myself and I
Me myself and I

Reputation: 4060

Why is assignment from string to char array missing the last character?

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"
}

Upvotes: 1

Views: 1673

Answers (4)

Qaz
Qaz

Reputation: 61910

Your problem is that you're passing a size of one too few to getline(), but there are better ways to do this. With C++11, you can emulate a modifiable character array (std::string has member functions for a non-modifiable one) by just using std::string:

std::string str = "Hello";
someFunc(&str[0], str.size());

Make sure, though, that someFunc does not overwrite the null character, even if it's with another null character. Pass the right size in to accommodate for that.

Without C++11, the easiest way is probably a vector:

std::string str = "Hello";
std::vector<char> vec(str.begin(), str.end());
someFunc(&vec[0], vec.size());

Upvotes: 1

csharpfolk
csharpfolk

Reputation: 4280

Check getline documentation, second argument specifies string size with null terminating character, so in your program you should use: ss.getline(&a[0], str.length() + 1);

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

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.

Upvotes: 11

Johnny Mnemonic
Johnny Mnemonic

Reputation: 3912

The second parameter of getline() is the maximum number of characters to write to a (including the null character).

Upvotes: 1

Related Questions