Writing a C ++ vector to an output file

ofstream outputFile ("output.txt");

if (outputFile.is_open())
{
     outputFile << "GLfloat vector[]={" <<  copy(vector.begin(), vector.end(), ostream_iterator<float>(cout, ", ")); << "}" << endl;
}
else cout << "Unable to open output file";

How to output a vector to a file with each float separated by commas? I would also like to avoid printing square brackets if possible.

+5
source share
4 answers
outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile , ", ")); 
                                                           ^^^^^^^^^^
outputFile << "}" << endl;
+6
source

First, you should not call a variable vector. Give it a name that is not a class name from the standard library.

Secondly, it ostream_iteratorwill add ','even after the last element of the vector, which may not be what you want (the separator must be a separator, and there is nothing to separate the last value of the vector from another value).

In C ++ 11, you can use a simple forrange-based loop :

outputFile << "GLfloat vector[]={";
auto first = true;
for (float f : v) 
{ 
    if (!first) { outputFile << ","; } 
    first = false; 
    outputFile << f; 
}
outputFile << "}" << endl;

++ 03 :

outputFile << "GLfloat vector[]={";
auto first = true;
for (vector<float>::iterator i = v.begin(); i != end(); ++i) 
{ 
    if (!first) { outputFile << ","; c++; } 
    first = false;
    outputFile << *i;
}
outputFile << "}" << endl;
+3

. , . :

outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile, ", "));
outputFile << "}" << endl;

The algorithm copysimply copies elements from one range to another. ostream_iterator- a special iterator that will actually insert (s <<) into the given stream when you do *it = item_to_insert;.

+1
source

Here is a good general (header-only) library that you just have to include in your code, and this will allow you to easily print any standard containers: http://louisdx.github.com/cxx-prettyprint/

0
source

All Articles