user1040781
user1040781

Reputation:

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.

I want a bunch of numbers from a csv file to be stored as a float array. 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 *'

Upvotes: 2

Views: 3068

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477040

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. You still have to tokenize the line into comma-separated pieces. find() and substr() may be a good start (e.g. see here), though perhaps a more general tokenization function would be more elegant.

Here's a tokenizer function that I stole from somewhere so long ago I can't remember, so apologies for the plagiarism:

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, ","); Now use std::atof() (or std::strtod()) on each string in the vector.


Here's a suggestion, just to give you some idea how one typically writes such code in 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

Upvotes: 4

Related Questions