0

How do I convert a string from my CSV file (excel worksheet) to a float value? Suppose that my CSV sheet contains:

0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1

and my code so far is:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    ifstream myfile("data1.csv");
    string line;
    getline(myfile,line,',');
    cout << line;
}

I am able to obtain line as a string, specifically type Ss but I need to convert the line into a float. How do I do that?

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • 1
    consider using a ibrary like [libcsv](https://github.com/rgamble/libcsv) for parsing csv files. – Sander De Dycker Jul 27 '18 at 09:02
  • 1
    First Google hit gives header-only library https://github.com/ben-strasser/fast-cpp-csv-parser. Or check this SO question https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c – Petr Javorik Jul 27 '18 at 09:16

1 Answers1

1

Keeping it plain C++ without additional libraries: Don't read strings, read floats:

float value;
char delim;
if( !( is >> value >> delim ) && ( delim == ',' || delim == '\n' ) )
    // format error
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • 13 9 C:\Users\Migs\Desktop\Test-Codes\testing2.cpp [Error] 'is' was not declared in this scope This was my error trying the code! – Miguel Lanto Jul 27 '18 at 10:42
  • That was a sample in which from context should be clear that `is` is a `std::ifstream`. Call it what you want. – Swordfish Jul 27 '18 at 10:47