C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

saving txt

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
MC felon
Guest





PostPosted: Sun Dec 17, 2006 10:10 am    Post subject: saving txt Reply with quote



hi
how do i save strings to txts and open them back?
Back to top
Ivan Novick
Guest





PostPosted: Sun Dec 17, 2006 10:10 am    Post subject: Re: saving txt Reply with quote



MC felon wrote:
Quote:
hi
how do i save strings to txts and open them back?
// write to file

#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::string str1("Hello");
std::string str2("World");
std::ofstream f("test.txt");
if (!f)
{
std::cerr << "can't open file\n";
exit(1);
}
f << str1 << std::endl;
f << str2 << std::endl;
return 0;
}
===============================
// read from file
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::ifstream f("test.txt");
if (!f)
{
std::cerr << "can't open file\n";
exit(1);
}
std::string str;
while(f >> str)
{
std::cout << str << std::endl;
}
return 0;
}
===============================
You may want to get a C++ reference book.
---
Ivan
http://www.0x4849.net
Back to top
Jacek Dziedzic
Guest





PostPosted: Sun Dec 17, 2006 10:11 am    Post subject: Re: saving txt Reply with quote



Ivan Novick wrote:
Quote:
MC felon wrote:
hi
how do i save strings to txts and open them back?
// write to file
#include <iostream
#include <fstream
int main(int argc, char** argv)
{
std::string str1("Hello");
std::string str2("World");
std::ofstream f("test.txt");
if (!f)
{
std::cerr << "can't open file\n";
exit(1);
}
f << str1 << std::endl;
f << str2 << std::endl;
return 0;
}
===============================
// read from file
#include <iostream
#include <fstream
int main(int argc, char** argv)
{
std::ifstream f("test.txt");
if (!f)
{
std::cerr << "can't open file\n";
exit(1);
}
std::string str;
while(f >> str)
{
std::cout << str << std::endl;
}
return 0;
}
===============================
You may want to get a C++ reference book.
---
Ivan
http://www.0x4849.net

I'd also advise the OP to read the strings back using
std::getline(), because the >> operator splits the input
on whitespace.

HTH,
- J.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.