|
-
September 26th, 2018, 08:06 AM
#9
Re: Why am I printing more characters that i expect?
 Originally Posted by 2kaud
Great! Another convert
Actually in your code you don't need to directly allocate any memory at all! You can let string take all the strain. Consider
Code:
//Size of the file.
file.seekg(0, std::ios::end);
std::streampos size = file.tellg();
file.seekg(0, std::ios::beg);
std::string data(size, 0);
//Read the data from the file.
file.read(data.data(), size);
//Close the string.
data[file.gcount()] = '\0';
data.resize(file.gcount());
//Close the file.
file.close();
That's a little tricky I read somewhere:
Accessing the value at data()+size() produces undefined behavior: There are no guarantees that a null character terminates the character sequence pointed by the value returned by this function. See string::c_str for a function that provides such guarantee.
A program shall not alter any of the characters in this sequence.
but i guess if you know what you are doing is fine.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|