Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write an STL string to a file 1

Status
Not open for further replies.

mbaranski

Programmer
Nov 3, 2000
421
US
I need to write an STL string to a file. I have a list of things (ASCII data) that I need to write to a file line by line. The line is like:
"mike", "baranski", "400", "The man"
and ends with a newline (the newline is included in the STL string).

I need help opeining a filehandle and printing these lines to it. I alreday have the loop set up to generate the data and set up the string, I just need help with the filehandle end and what to write to it.

An stl string can be turned into a c-string by calling stlStringName.c_str(); If you know of a way to write a c null terminated string to a file that's great, too.

Thanks!! As always, I hope that helped!

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
mbaranski,

#include <fstream>
#include <string>
using namespace std;

typedef vector<string> STRVECTOR;
typedef STRVECTOR::iterator STRVECTORIT;

void writeFile(){

STRVECTOR v;
v.push_back( &quot;mike, baranski, 400, The man\r\n&quot;);
v.push_back( &quot;pete, albano, 500, The ?\r\n&quot;);

ofstream ofs(&quot;test.txt&quot;);
for(STRVECTORIT it = v.begin(); it != v.end(); it++)
ofs << *it;

ofs.close();
}

void main()
{
writeFile();
}


Hope this helps
-pete
 
OK, that should work. One more question, though, what is \r before the newline? Is that a carrige return? If it is, UNIX doesen't need that, does it? If it is app. dependent, I can find out if I need it or not. As always, I hope that helped!

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
> Is that a carrige return? If it is, UNIX doesen't need that, does it?

Yes, No.

Just use a preprocessor conditional block if you want the code to be cross-platform. Something like:

#ifdef _UNIX
const char* NEWLINE = &quot;\n&quot;;
#else
const char* NEWLINE = &quot;\r\n&quot;;
#endif

Good luck
-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top