How to read a file into vector in C++?(如何在C++中将文件读入向量?)
问题描述
我需要从 .data
或 .txt
文件中读取每行包含一个新的 float
数字到一个向量中.
I need to read from a .data
or .txt
file containing a new float
number on each line into a vector.
我已经广泛搜索并应用了许多不同的方法,但每次我得到相同的结果时,Main.size()
的 0
和错误说明向量下标超出范围"
,所以很明显向量只是没有将任何内容读入文件.
I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size()
of 0
and an error saying "Vector Subscript out of Range"
, so evidently the vector is just not reading anything into the file.
注意:该文件既在文件夹中,也包含在 VS 项目中.
Note: the file is both in the folder and also included in the VS project.
无论如何,这是我的代码:
Anyway, here's my code:
我得到的结果总是很简单:
The result I get is always simply:
推荐答案
你的循环错了:
试试这个:
此外,将数字读入向量并将它们写入标准输出的更惯用的方法是:
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
尽管您应该检查 ifstream
的状态是否有读取错误.
although you should check the status of the ifstream
for read errors.
这篇关于如何在C++中将文件读入向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!