在c++中如何将字符串数组转换为浮点数组

How do you convert an array of strings to an array of floats in c++?

本文关键字:数组 转换 字符串 c++      更新时间:2023-10-16

基本上,我对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