saving txt

I

Ivan Novick

MC said:
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::eek:fstream 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.
 
J

Jacek Dziedzic

Ivan said:
// write to file
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::string str1("Hello");
std::string str2("World");
std::eek:fstream 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.

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

HTH,
- J.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top