从制表符分隔的文件中读取2D数据并存储在矢量C++中
Reading 2D data from tab delimited file and store in vector C++
我正在尝试读取以下格式的文本文件:
5
1.00 0.00
0.75 0.25
0.50 0.50
0.25 0.75
0.00 1.00
代码为:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int totalDataPoints; // this should be the first line of textfile i.e. 5
std::vector<double> xCoord(0); //starts from 2nd line, first col
std::vector<double> yCoord(0); //starts from 2nd line, second col
double tmp1, tmp2;
int main(int argc, char **argv)
{
std::fstream inFile;
inFile.open("file.txt", std::ios::in);
if (inFile.fail()) {
std::cout << "Could not open file" << std::endl;
return(0);
}
int count = 0;
while (!inFile.eof()) {
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
count++;
}
for (int i = 0; i < totalDataPoints; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
return 0;
}
我没有得到结果。我的最终目标是将其作为函数,并将x,y值作为类的对象进行调用。
int totalDataPoints;
是一个全局变量,由于您没有用值初始化它,因此它将被初始化为0。然后在你的for循环中
for (int i = 0; i < totalDataPoints; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
因为i < totalDataPoints
(0 < 0
)就是false
,所以你要做任何事情。我怀疑你想用
for (int i = 0; i < count; ++i) {
std::cout << xCoord[i] << " " << yCoord[i] << std::endl;
}
或者有
totalDataPoints = count;
在for循环之前。
我还建议您不要使用while (!inFile.eof())
来控制文件的读取。修复它你可以使用
while (inFile >> tmp1 && inFile >> tmp2) {
xCoord.push_back(tmp1);
yCoord.push_back(tmp2);
count++;
}
这将确保循环只在有数据要读取时运行。有关更多信息,请参阅:为什么"while(!feof(file))"总是错误的?
只需要对代码进行简单的更改。你不能拿第一行file.txt
提供的totalDataPoints
。然后你把每一行都抄到最后。
int count = 0;
inFile>>totalDataPoints;
while (!inFile.eof()) {
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
count++;
}
通过循环,您可以这样做,这里int count = 0
是不必要的:
inFile>>totalDataPoints;
for (int i=0; i<totalDataPoints; i++)
{
inFile >> tmp1;
xCoord.push_back(tmp1);
inFile >> tmp2;
yCoord.push_back(tmp2);
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在c++中获取两个大int,并将它们存储在数组中
- 在reactor中存储eventHandlers的最佳方式是什么