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:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<double> Main;
int count;
string lineData;
double tmp;
ifstream myfile ("test.data", ios::in);
double number;
myfile >> count;
for(int i = 0; i < count; i++) {
myfile >> tmp;
Main.push_back(tmp);
cout << count;
}
cout << "Numbers:
";
cout << Main.size();
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '
';
}
cin.get();
return 0;
}
我得到的结果总是很简单:
The result I get is always simply:
Numbers:
0
推荐答案
你的循环错了:
for (int i=0; i=((Main.size())-1); i++) {
试试这个:
for (int i=0; i < Main.size(); i++) {
此外,将数字读入向量并将它们写入标准输出的更惯用的方法是:
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy
int main()
{
std::ifstream is("numbers.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
// print the numbers to stdout
std::cout << "numbers read in:
";
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
}
尽管您应该检查 ifstream
的状态是否有读取错误.
although you should check the status of the ifstream
for read errors.
这篇关于如何在C++中将文件读入向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在C++中将文件读入向量?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01