我正在尝试将字符串向量转换为浮点向量,理想情况下我想将其转换为浮点数组,因为这对我来说更容易使用但是从研究中我已经了解到向量优于数组。这是代码我仍然是一个初学c ++编码器,我只是有点了解在代码中发生了什么。当我尝试运行它时程序一直给我和错误我不明白为什么但我知道这与我将字符串向量转换为浮点数的尝试有关。
#include <vector>
#include <string>
#include <iostream>
#include "sqlite3.h"
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
sqlite3* db;
using Records = vector<Record>;
int select_callback(void *p_data, int num_fields, char **p_fields, char **p_col_names)
{
Records* records = static_cast<Records*>(p_data);
try {
records->emplace_back(p_fields, p_fields + num_fields);
}
catch (...) {
// abort select on failure, don't let exception propogate thru sqlite3 call-stack
return 1;
}
return 0;
}
Records select_stmt(const char* stmt)
{
Records records;
char *errmsg;
int ret = sqlite3_exec(db, stmt, select_callback, &records, &errmsg);
if (ret != SQLITE_OK) {
std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
else {
std::cerr << records.size() << " records returned.\n";
}
return records;
}
void sql_stmt(const char* stmt)
{
char *errmsg;
int ret = sqlite3_exec(db, stmt, 0, 0, &errmsg);
if (ret != SQLITE_OK) {
std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
}
int main()
{
if (sqlite3_open("BandDia.db", &db) != SQLITE_OK) {
std::cerr << "Could not open database.\n";
return 1;
}
Records records = select_stmt("SELECT * FROM k_EnergyEig_T2 ");
sqlite3_close(db);
vector<float> v;
istringstream iss(Records);
std::copy(std::istream_iterator<float>(iss),
std::istream_iterator<float>(),
std::back_inserter(v));
// Put the result on standard out
std::copy(v.begin(), v.end(),
std::ostream_iterator<float>(std::cout, ", "));
std::cout << "\n";
/* for (auto& record : records) {
// do something with your records
puts("Hello,World");
}*/
return 0;
}
答案 0 :(得分:0)
如果我正确理解了这个问题,你有一个包含逗号分隔值的字符串,你想将它转换成一个浮点数组。
我要做的第一件事就是将字符串拆分为子字符串。每个子字符串将包含一个值。 Examples of this can be found here.
接下来要做的是迭代这些字符串并将它们转换为浮点数。 For this you can use the atof
function. atof
代表&#39; a&#39; (字符串)到&#39; f&#39; (浮动)。请注意,您可以使用s.c_str()
轻松地将std :: string转换为c字符串。
最后,在这里使用向量可能更好,因为它们可以动态调整大小。如果您真的想将输出转换为数组,则可以始终执行此操作:
float* a = new float[v.size()];
memcpy(a, &v[0], sizeof(float) * v.size());