简体   繁体   English

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

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

Basically, I know virtually nothing about C++ and have only programmed briefly in Visual Basic. 基本上,我对C ++几乎一无所知,并且只在Visual Basic中进行了简短的编程。

I want a bunch of numbers from a csv file to be stored as a float array. 我想将csv文件中的一堆数字存储为float数组。 Here is some code: 这是一些代码:

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]);
    ...
  }
  ...
}

Anyways it says: 无论如何,它说:

error C2664: 'atof' : cannot convert parameter 1 from 'std::string' to 'const char *' 错误C2664:'atof':无法将参数1从'std :: string'转换为'const char *'

Well, you'd have to say atof(stropenprice[x].c_str()) , because atof() only operates on C-style strings, not std::string objects, but that's not enough. 好吧,您不得不说atof(stropenprice[x].c_str()) ,因为atof()仅适用于C样式的字符串,而不适用于std::string对象,但这还不够。 You still have to tokenize the line into comma-separated pieces. 您仍然必须将行标记为逗号分隔的部分。 find() and substr() may be a good start (eg see here ), though perhaps a more general tokenization function would be more elegant. find()substr()可能是一个不错的开始(例如, 参见此处 ),尽管也许更通用的标记化功能会更优雅。

Here's a tokenizer function that I stole from somewhere so long ago I can't remember, so apologies for the plagiarism: 这是我很久以前从不记得的地方偷来的一个分词器功能,为for窃道歉:

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;
}

Usage: std::vector<std::string> v = tokenize(line, ","); 用法: std::vector<std::string> v = tokenize(line, ","); Now use std::atof() (or std::strtod() ) on each string in the vector. 现在在向量中的每个字符串上使用std::atof() (或std::strtod() )。


Here's a suggestion, just to give you some idea how one typically writes such code in C++: 这是一个建议,只是为了让您了解一下通常如何用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM