在c++中将.txt文件列存储到数组中
Store a .txt file columns into an array in c++
我是一个编程新手,所以我有什么可能是一个基本的问题。我目前有一个文本文件2列。每行有x和y个数字,用空格分隔。以下是文件的前五行:
120 466
150 151
164 15
654 515
166 15
我想读取数据并将它们存储到x和Y列中,然后在程序的其他地方调用数据,例如x[I]和Y [I]。比如说,我不知道行数。这是我的代码的一部分,我试图做到这一点。
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
double X[];
double Y[];
ifstream inputFile("input.txt");
string line;
while (getline(inputFile, line))
{
istringstream ss(line);
double x,y;
ss >> x >> y;
X = X + [x];
Y = Y + [y];
return 0;
}
}
最好使用vector:
vector<double> vecX, vecY;
double x, y;
ifstream inputFile("input.txt");
while (inputFile >> x >> y)
{
vecX.push_back(x);
vecY.push_back(y);
}
for(int i(0); i < vecX.size(); i++)
cout << vecX[i] << ", " << vecY[i] << endl;
推荐的方法是使用一个或两个std::vector<double>
(每列一个),因为可以很容易地向它们添加值。
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组