i have following code for copying content of vector into file
#include<iterator>
#include<algorithm>
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;
void dump(vector<int>& v){
ofstream out1("C\\Users\\datuashvili\\Desktop\\vector.txt");
if(!out1){
exit(1);
}
copy(v.begin(),v.end(),ostream_iterator<int>(out1," "));
}
int main(){
ofstream out1("C\\Users\\datuashvili\\Desktop\\vector.txt");
vector<int>v;
v.push_back(100);
v.push_back(200);
v.push_back(300);
v.push_back(500);
v.push_back(1000);
dump(v);
return 0;
}
but when i simple run this code,,there is not written into file which is created on desktop,why?could you tell me what is wrong with this code?
EDITED:
here is edited code which also does not work doesn’t open files and also does not write,two version
1.version
#include<iterator>
#include<algorithm>
#include<fstream>
#include<ostream>
#include<iostream>
#include<vector>
using namespace std;
void dump( vector<int>& v){
ofstream out1(("C:\\vector.txt"));
if(!out1){
exit(1);
}
copy(v.begin(),v.end(),ostream_iterator<int>(out1," "));
out1.close();
}
int main(){
vector<int>v;
v.push_back(100);
v.push_back(200);
v.push_back(300);
v.push_back(500);
v.push_back(1000);
dump(v);
return 0;
}
2.
#include<iostream>
#include<fstream>
#include<ostream>
#include<vector>
#include<algorithm>
#include<iterator>
using namespace std;
template<typename T>
void writeTo(const std::string& filepath,const vector<T>& data)
{
ofstream filestream("C:\\vector.txt");
std::copy(data.begin(),data.end(),std::ostream_iterator<T>( filestream," "));
filestream.close();
}
int main(){
vector<int>test;
test.push_back(1);
writeTo<int>("C:\\vector.txt", test);
return 0;
}
I suspect the problem is this:
should be;
You could have found this out on your own by running under a debugger, observing the exit status of your program, or by adding print statements to your program.
In a debugger, you would have stepped through your code and discovered that you hit “exit(1)”. Alternatively, you could have added something like
cout << "Can't open file!\n";to yourifstatement.