在c++中如何将字符串数组转换为浮点数组
How do you convert an array of strings to an array of floats in c++?
基本上,我对c++一无所知,只在Visual Basic中做过简单的编程。
我想要一堆数字从csv文件被存储为一个float
数组。下面是一些代码:
string stropenprice[702];
float openprice[702];
int x=0;
ifstream myfile ("open.csv");
if (myfile.is_open())
{
while ( myfile.good() )
{
x=x+1;
getline (myfile,stropenprice[x]);
openprice[x] = atof(stropenprice[x]);
...
}
...
}
无论如何它说:
错误C2664: 'atof':无法将参数1从'std::string'转换为'const char *'
嗯,你必须说atof(stropenprice[x].c_str())
,因为atof()
只操作c风格的字符串,而不是std::string
对象,但这还不够。您仍然需要将该行标记为逗号分隔的部分。find()
和substr()
可能是一个很好的开始(例如,见这里),尽管可能更通用的标记化函数会更优雅。
这是我很久以前从某个地方偷来的一个标记器函数,我不记得了,所以为剽窃道歉:
std::vector<std::string> tokenize(const std::string & str, const std::string & delimiters)
{
std::vector<std::string> tokens;
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
用法:std::vector<std::string> v = tokenize(line, ",");
现在对vector中的每个字符串使用std::atof()
(或std::strtod()
)。
这里有一个建议,只是给你一些关于如何在c++中编写这样的代码的想法:
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
// ...
std::vector<double> v;
std::ifstream infile("thefile.txt");
std::string line;
while (std::getline(infile, line))
{
v.push_back(std::strtod(line.c_str(), NULL)); // or std::atof(line.c_str())
}
// we ended up reading v.size() lines
相关文章:
- 如何在C++中将数组转换为矢量指针
- 将C++中的数组转换为字符串
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 将 int 数组转换为 std::vector<int*>
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将字符数组转换为时间结构
- 将字节数组转换为多维数组
- 可视化 如何在C++中将字符数组转换为 FILE 类型
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- C++如何将字符数组转换为字节向量(向量<byte>)
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 无法将字符数组转换为包含 utf-8 字符的字符串
- 如何使用 C++将 2D RGB 数组转换为 dds 文件?
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 将 int 数组转换为带有小数C++的双精度数组
- 使用 .data() 将字符数组转换为 std::string 不会转换整个数组
- 将字符数组转换为整数值