gpt4 book ai didi

c++ - 将 .txt 文件列存储到 C++ 中的数组中

转载 作者:太空狗 更新时间:2023-10-29 20:54:06 25 4
gpt4 key购买 nike

我是编程新手,所以我有一个可能是基本问题。我目前有一个包含 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;

关于c++ - 将 .txt 文件列存储到 C++ 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com