 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
MC felon Guest
|
Posted: Sun Dec 17, 2006 10:10 am Post subject: saving txt |
|
|
hi
how do i save strings to txts and open them back? |
|
| Back to top |
|
 |
Ivan Novick Guest
|
Posted: Sun Dec 17, 2006 10:10 am Post subject: Re: saving txt |
|
|
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
|
Posted: Sun Dec 17, 2006 10:11 am Post subject: Re: saving txt |
|
|
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 |
|
 |
|
|
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
|
|