Deep
Deep

Reputation: 646

How to obtain a floating point value from a string?

I am using istringstream from <sstream> header library to process the string, which works well for integer values but not for floats. The output I get are all integers for the below code.

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

using std::istringstream;
using std::string;
using std::cout;

int main () 
{
    string a("1 2.0 3");

    istringstream my_stream(a);

    int n;
    float m, o;
    my_stream >> n >> m >> o;
    cout << n << "\n";
    cout << m << "\n";
    cout << o << "\n";
}

I want output of m to be 2.0, but I am getting it as just integer 2. Am I missing something here, or should I be using a something else?

Upvotes: 0

Views: 73

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Here you go:

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip> // << enable to control stream formatting

using std::istringstream;
using std::string;
using std::cout;

int main () 
{
    string a("1 2.0 3");

    istringstream my_stream(a);

    int n;
    float m, o;
    my_stream >> n >> m >> o;
    cout << std::fixed; // << One way to control how many digits are outputted
    cout << n << "\n";
    cout << m << "\n";
    cout << o << "\n";
}

Output

1
2.000000
3.000000

You can use more stream formatting parameters to control how many digits you want to see exactly.
You shouldn't confuse values and representation.

Upvotes: 2

Related Questions