简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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