将C++向量写入输出文件

5
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";

我该如何将一个向量输出到文件中,使每个浮点数之间用逗号隔开?如果可能的话,我也想避免打印方括号。
4个回答

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

6
除了代码之外,如果能得到您所做的解释,那将是非常棒的。 - abcd

3
首先,不应该将变量命名为vector,请给它一个不是标准库类名称的名称。
其次,ostream_iterator会在向量的最后一个元素之后添加一个',',这可能不是您想要的(分隔符应该是一个分隔符,并且没有任何内容可以将向量的最后一个值与其他值分隔开)。
在C++11中,您可以使用简单的基于范围的for循环:
outputFile << "GLfloat vector[]={";
auto first = true;
for (float f : v) 
{ 
    if (!first) { outputFile << ","; } 
    first = false; 
    outputFile << f; 
}
outputFile << "}" << endl;

在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;

1
你可能把那个for循环搞混了。 - David G
没问题。我可以问一下吗:最近为什么没有回答问题? - David G
@0x499602D2:我有很多工作要做,还有一些健康问题迫使我重新调整了在SO上的活动优先级,但我计划很快回来 :) - Andy Prowl
1
@AndyProwl 'c++' 应该放在 if 块外面吗?如果不是,c 将永远不会从 0 增加。另外,使用布尔值可能比使用整数更好。 - aatish
1
@user19448:确实,那是个疏忽。我已经编辑了答案,谢谢。 - Andy Prowl
显示剩余2条评论

2

您已经尝试将解决方案插入到流插入中。这不是它的工作方式。它应该是一个单独的行:

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

copy算法只是将一个范围内的元素复制到另一个范围中。ostream_iterator是一种特殊的迭代器,当你执行*it = item_to_insert;时,它实际上会将内容(使用<<)插入给定的流中。


尽管包含了以下所有内容,它仍然显示copy_n未声明:#include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator> #include <algorithm> #include <stdlib.h> - user2136754

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接