作者:咖啡十伴侣 | 来源:互联网 | 2023-05-19 00:40
I would like to load the contents of a text file into a vector
(or into any char input iterator, if that is possible). Currently my code looks like this:
我想将文本文件的内容加载到vector
(或者加入任何char输入迭代器,如果可能的话)。目前我的代码如下所示:
std::vector vec;
std::ifstream file("test.txt");
assert(file.is_open());
while (!(file.eof() || file.fail())) {
char buffer[100];
file.read(buffer, 100);
vec.insert(vec.end(), buffer, buffer + file.gcount());
}
I do not like the manual use of a buffer (Why 100 chars? Why not 200, or 25 or whatever?), or the large number of lines that this took. The code just seems very ugly and non-C++. Is there a more direct way of doing this?
我不喜欢手动使用缓冲区(为什么100个字符?为什么不是200个,或者25个或者其他什么?),或者是这么多行。代码看起来非常丑陋而且非C ++。有更直接的方法吗?
5 个解决方案