Outputting a vector of string objects to a file
I'm trying to output a vector of string objects to a file. However, my code only out开发者_C百科puts the first two elements of each string.
The piece of code below writes:
1
1
to a file. Rather then:
01-Jul-09
01-Jul-10
which is what I need.
ofstream file("dates.out");
vector<string> Test(2);
Test[0] = "01-Jul-09";
Test[1] = "01-Jul-10";
for(unsigned int i=0; i<Test.size(); i++)
file << Test[i] << endl;
file.close();
Is not clear to me what could be going wrong as I have used string objects before in similar contexts.
Any help would be welcome!
As already observed, the code appears fine, so:
- Are you looking at the right
dates.out
after your program runs? Did you verify the date/time on the file you're looking at to make sure it isn't previous data? - Do you have permission to write to the file? Perhaps your program is failing to overwrite existing data.
- Did you show us ALL the important code? Are there any other function calls we need to know about? Does the code in Marcelo/ereOn's answers produce the same problem as in your question?
- Are you sure that you're running the binary you think you are? (PATH issues possibly).
The following code works as expected:
marcelo@macbookpro-1:~/play$ cat dateout.cc
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ofstream file("dates.out");
vector<string> Test(2);
Test[0] = "01-Jul-09";
Test[1] = "01-Jul-10";
for(unsigned int i=0; i<Test.size(); i++)
file << Test[i] << endl;
file.close();
}
marcelo@macbookpro-1:~/play$ make dateout && ./dateout
g++ dateout.cc -o dateout
marcelo@macbookpro-1:~/play$ cat dates.out
01-Jul-09
01-Jul-10
marcelo@macbookpro-1:~/play$
精彩评论