Writing and reading string class

Started by
2 comments, last by The C modest god 20 years, 3 months ago
I have the following code: string a="test", b; ofstream outf("a.fl", ios::binary); ifstream inf("a.fl", ios::binary); outf<>b; inf.close(); The value of b is test and some junk characters afterwards. The outf<<a don''t put an end of string charcter at the end? Why this happens? and how can I write and read a string class simply?
It's all about the wheel.Never blindly trust technoligy.I love my internal organs.Real men don't shower.Quote:Original post by Toolmaker Quote:Original post by The C modest godHow is my improoved signature?It sucks, just like you.
Advertisement
It''s working perfectly fine for me.

$ cat foo.cc#include <iostream>#include <fstream>#include <string>int main(){   std::string a="test", b;   std::ofstream outf("a.fl", std::ios::binary);   std::ifstream inf("a.fl", std::ios::binary);   outf<<a;   outf.close();   inf>>b;   inf.close();   std::cout << b << std::endl;}


And don''t use [code‍] blocks if you''re not willing to replace your < with &lt;
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I have noticed that when I read the string, I get the string and the string I wrote afterwards. I assume that writting a string in binary does not put ''\0''.
Therefore I need to put it explicitly.
My question is, does endl functions as ''\0''?
It's all about the wheel.Never blindly trust technoligy.I love my internal organs.Real men don't shower.Quote:Original post by Toolmaker Quote:Original post by The C modest godHow is my improoved signature?It sucks, just like you.
No. endl works as ''\n'', and >> reads whitespace-delimited words. Opening a file in ''binary mode'' doesn''t mean the data is read/written in binary, only that (platform-dependent) newline translation is not done.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement