M
MC felon
hi
how do i save strings to txts and open them back?
how do i save strings to txts and open them back?
// write to fileMC said:hi
how do i save strings to txts and open them back?
Ivan said:// write to file
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::string str1("Hello");
std::string str2("World");
std: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.
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.