[英]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 do I output a vector to a file, with each float separated by commas? 如何将矢量输出到文件,每个浮点数用逗号分隔? I would also like to avoid printing square brackets if possible.
如果可能的话,我还想避免打印方括号。
outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile , ", "));
^^^^^^^^^^
outputFile << "}" << endl;
First, you shouldn't call your variable vector
. 首先,你不应该调用你的变量
vector
。 Give it a name which is not the name of a class from the Standard Library. 给它一个名称,它不是标准库中类的名称。
Secondly, ostream_iterator
will append a ','
even after the last element of the vector, which may not be what you want (a separator should be a separator , and there's nothing to separate the last value of the vector from a further value). 其次,
ostream_iterator
会在向量的最后一个元素之后附加一个','
,这可能不是你想要的(分隔符应该是一个分隔符 ,并且没有什么可以将向量的最后一个值与另一个值分开)。
In C++11, you could use a simple range-based for
loop: 在C ++ 11中,您可以使用一个简单的基于范围的
for
循环:
outputFile << "GLfloat vector[]={";
auto first = true;
for (float f : v)
{
if (!first) { outputFile << ","; }
first = false;
outputFile << f;
}
outputFile << "}" << endl;
In C++03, it is going to be just a bit more verbose: 在C ++ 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;
You've taken the solution and attempted to stick it into the stream insertion. 您已采用该解决方案并尝试将其粘贴到流插入中。 That's not how it works.
这不是它的工作原理。 It should be a separate line:
它应该是一个单独的行:
outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile, ", "));
outputFile << "}" << endl;
The copy
algorithm simply copies elements from one range to another. copy
算法只是将元素从一个范围复制到另一个范围。 ostream_iterator
is a special iterator that will actually insert (with <<
) into the given stream when you do *it = item_to_insert;
ostream_iterator
是一个特殊的迭代器,当你执行*it = item_to_insert;
时,它会实际插入(带有<<
)到给定的流中*it = item_to_insert;
. 。
这是一个很好的通用(仅限标题)库,您只需要在代码中包含它,它将允许您轻松打印任何标准容器: http : //louisdx.github.com/cxx-prettyprint/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.