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?

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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!
That was a sample in which from context should be clear that is is a std::ifstream. Call it what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.