views:

93

answers:

2

I'm trying to output a vector of string objects to a file. However, my code only outputs 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!

A: 

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$ 
Marcelo Cantos
+1  A: 

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).
Mark B
I figured out what the problem is:The code is fine. The problem was due to another application (Matlab) which uses the dates.out file and expected a different format. Thanks for the help!
Wawel100
A related issue is that I'm outputing strings like: file << "Some Text[^\n]" << endl; Now the \n leads to a new line in the file which is not what I want - ideally I just want: Some Text[\n]How can I get C++ to treat \n as just part of the string?
Wawel100
`\\n` will put the text `\n` into the file.
Mark B