| View previous topic :: View next topic |
| Author |
Message |
Engineer Expert Cheater
Reputation: 1
Joined: 25 Nov 2007 Posts: 170
|
Posted: Mon Aug 23, 2010 8:28 am Post subject: C++ ofstream.write(string, int) Creating unrelated text? |
|
|
Hello, I wrote this so I can cin>> something into a file
| Code: |
void selectedCreate()
{
textInScreen = "";
string filelocation = "";
cout << "Save as file (files might be overwritten): ";
cin >> filelocation;
ofstream outputstream (filelocation.c_str(), ios::ate);
if (!outputstream.is_open())
{
cout << "Error creating/opening file";
}
else
{
cout << endl << endl;
string textToSave = "";
cin >> textToSave;
textInScreen = textToSave;
outputstream.write(textToSave.c_str(), 249);
}
outputstream.close();
} |
It seems to work fine, but when I open the text files, I get messy results that normally relate to my steam team fortress folder and windir, example
| Code: |
watthefuck am\steama l l °> °> am fortress 2\tf windir=C:\WINDOWS E ] ä |
(the only thing i wrote was 'watthefuck')
I really don't know why this happens, any fixes?
edit: probably writing the default vars in cmd? like computername, windir, etc?
|
|
| Back to top |
|
 |
XaLeX Expert Cheater
Reputation: 0
Joined: 19 Aug 2008 Posts: 226
|
Posted: Mon Aug 23, 2010 9:14 am Post subject: Re: C++ ofstream.write(string, int) Creating unrelated text? |
|
|
| Engineer wrote: | | outputstream.write(textToSave.c_str(), 249); |
that line of code reads 249 bytes from memory and writes them to the file (and goes past the null terminator). change the 249 (why 249?) to textToSave.length and it should work.
|
|
| Back to top |
|
 |
Engineer Expert Cheater
Reputation: 1
Joined: 25 Nov 2007 Posts: 170
|
Posted: Mon Aug 23, 2010 10:18 am Post subject: Re: C++ ofstream.write(string, int) Creating unrelated text? |
|
|
| XaLeX wrote: | | Engineer wrote: | | outputstream.write(textToSave.c_str(), 249); |
that line of code reads 249 bytes from memory and writes them to the file (and goes past the null terminator). change the 249 (why 249?) to textToSave.length and it should work. |
That only saves the first word on the string. I guess it would do the same thing with my broken code anyway
|
|
| Back to top |
|
 |
Flyte Peanuts!!!!
Reputation: 6
Joined: 19 Apr 2006 Posts: 1887 Location: Canada
|
Posted: Mon Aug 23, 2010 12:59 pm Post subject: |
|
|
| Consider using std::getline, and fstream.
|
|
| Back to top |
|
 |
|