我目前在尝试使用结构从文本文件中提取数据然后将其存储到 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/