Eomer sade:
How do i save an int value or an array to a .txt file?
which file to include? what is the function? what is the syntax? what
are the common problems?
Thanks in advance,
Eomer
I recommend buying a book covering basic io/file operations.
Or the internet has many tutorials on C++ IO operations.
<fstream> has everything you need, well almost. Observe:
//---------------------------------------------------------------------------
#include <ostream>
#include <fstream>
#include <iterator>
#include <algorithms>
#include <vector>
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// Save and restore single integer
{
std:
fstream out("persistency.txt");
out << 7;
out.close();
int i = 0;
std::ifstream in("persistency.txt");
in >> i;
in.close();
std::cout << i << std::endl;
}
// Save and restore integer vector
{
std::vector<int> v;
std::generate_n(std::back_inserter(v),10,std::rand);
// Open file
std:
fstream out("array-persistency.txt");
// Copy v to file
std::copy(v.begin(),v.end(),std:
stream_iterator<int>(out," "));
out.close();
// Copy v to std::cout
std::copy(v.begin(),v.end(),
std:
stream_iterator<int>(std::cout," "));
v.clear();
std::endl(std::cout);
std::ifstream in("array-persistency.txt");
// Copy file to v
std::copy(std::istream_iterator<int>(in),
std::istream_iterator<int>(), std::back_inserter(v));
// Copy v to std::cout
std::copy(v.begin(),v.end(),
std:
stream_iterator<int>(std::cout," "));
in.close();
}
return 0;
}
TB