Why the output is messy code

I use the below code:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>

int main()
{

std::ofstream fs("file.txt");
std::string str;
std::cin>>str;
int size = str.size();
char* buf = new char[size];
fs.write(buf, size);
delete buf;
fs.close();

}

but When I unput some normal word ,then I got those messy code
Are you asking why the file ends up with garbage in it? That's because you allocate a C-string but don't initialize it, so it's contents are garbage. You then write that garbage to the file. Try assigning str.c_str() to buf via strcpy() or simply write() str.c_str() to the file.
@Zhuge,

I can't thank you enough , when I insert
buf = const_cast<char*>(str.c_str());
before fs.write(buf, size);
and it works , :)
termination character is needed for c strings that are not of the length of the array specified. str.c_str() fixes that delimiter (\0) to the end of the string you typed. The memory is allocated the the length, so without that termination character, you read the whole array allocation by the character array.

http://en.wikipedia.org/wiki/C_string#Standard_terms_and_definitions_in_C
Last edited on
termination character is needed for c strings that are not of the length of the array specified.

Hm? When a C string is being read, it will happily go beyond the array bounds if no null terminator can be found, which would result in undefined behavior. And he's writing the entire string without the null terminator, regardless of how much memory the string instance has allocated internally.

const_cast should be avoided like the plague. It is only needed in some cases when calling functions of legacy libraries that don't take const pointers when they should.
In this case, it should be: const char* buf = str.c_str();
Or just: fs.write(str.c_str(),size);
Topic archived. No new replies allowed.