c++ - 将文本文件中的数据提取到结构中

标签 c++ vector struct text-files

我目前在尝试使用结构从文本文件中提取数据然后将其存储到 vector 中时遇到问题。但无论我做什么,除非我将 float,int 的值更改为字符串,否则它总是会给我这样的错误:

MissionPlan.cpp:190: error: invalid conversion from ‘void*’ to ‘char**’
MissionPlan.cpp:190: error: cannot convert ‘float’ to ‘size_t*’ for argument ‘2’ to ‘__ssize_t getline(char**, size_t*, FILE*)

这是我的结构:

struct CivIndexDB {
float civInd;
int x;
int y;
}

这是我的示例文本文件:

3.2341:2:3
1.5234:3:4

这是我用来从文本文件中提取数据然后将其存储到 vector 中的代码:

string line = "";
while (getline(civIndexFile,line)) {
    stringstream linestream(line);

    getline(linestream,civDb.civInd,':');
    getline(linestream,civDb.x,':');
    getline(linestream,civDb.y);
    civIndexesList.push_back(civDb);            
}

将结构中的变量类型更改为字符串不是我稍后在应用程序中需要的,我需要根据其浮点值对 vector 值进行排序。

感谢您提供的任何帮助。谢谢!

最佳答案

如果文件格式固定,我建议在不调查您的确切问题/错误的情况下,最简单的方法是:

char ch; // For ':'
while (civIndexFile >> civDb.civInd >> ch >> civDb.x >> ch >> civDb.y )
{
    civIndexesList.push_back(civDb); 
}

编辑

要对浮点值进行排序,您可以重载 <运算符(operator):

struct CivIndexDB {
  float civInd;
  int x;
  int y;

  bool operator <(const CivIndexDB& db) const
  {
    return db.civInd > civInd;
  }
};

然后使用std::sort :

std::sort(civIndexesList.begin(), civIndexesList.end() );

关于c++ - 将文本文件中的数据提取到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331763/

相关文章:

c++ - sizeof() 是否显示 C++ 类开销?

c++ - 比较两个 vector 中的元素时出现错误 - 我做错了什么吗?

c++ - vector 和迭代器,打印出值而不是内存地址

struct - Common Lisp 按顺序处理结构槽

c++ - 为什么这个 MEX 函数会产生意想不到的结果?

c++ - 您如何使用 "function type"?

c++ - 如何将基于通用迭代器的算法与基于实现的算法结合起来?

matrix - (Unity3D)MultiplyPoint 和 MultiplyPoint3x4 之间的区别

jquery - 任意对象成员选择 C++

c - times() 返回的结构 tms 值全为零或负数