如何从字符串获得浮点值

How to obtain a floating point value from a string?

本文关键字:字符串      更新时间:2023-10-16

我正在使用 <sstream> header库中的 istringstream来处理字符串,该字符串适用于 integer 值值,但对于 floats 。我获得的输出都是以下代码的整数。

#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";
}

我希望m的输出为2.0,但我将其视为整数2。我在这里错过了什么,还是应该使用其他东西?

您去这里:

#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";
}

输出

1
2.000000
3.000000

您可以使用更多的流格式参数来控制要准确看到的数字。
您不应该混淆价值和表示形式。