(C++)std::istringstream从字符串到双精度最多可读取6位数字

(C++) std::istringstream reads up to 6 digits from string to double

本文关键字:读取 数字 6位 双精度 字符串 C++ std istringstream      更新时间:2023-10-16

各位!我已经为这个问题挣扎了一段时间,到目前为止我还没有找到任何解决方案

在下面的代码中,我用一个数字初始化一个字符串。然后我使用std::istringstream将测试字符串内容加载到double中。然后我计算两个变量。

#include <string>
#include <sstream>
#include <iostream>
std::istringstream instr;
void main()
{
    using std::cout;
    using std::endl;
    using std::string;
    string test = "888.4834966";
    instr.str(test);
    double number;
    instr >> number;
    cout << "String test:t" << test << endl;
    cout << "Double number:t" << number << endl << endl;
    system("pause");
}

当我运行.exe时,它看起来像这样:

字符串测试:888.4834966
双位数888.483
按任意键继续。

该字符串有更多的数字,看起来std::istringstream只加载了10个数字中的6个。如何将所有字符串加载到双变量中?

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
std::istringstream instr;
int main()
{
    using std::cout;
    using std::endl;
    using std::string;
    string test = "888.4834966";
    instr.str(test);
    double number;
    instr >> number;
    cout << "String test:t" << test << endl;
    cout << "Double number:t" << std::setprecision(12) << number << endl << endl;
    system("pause");
    return 0;
}

它读取所有的数字,但它们并没有全部显示出来。您可以使用std::setprecision(在iomanip中找到)来更正此问题。还要注意,void main不是标准的,您应该使用int main(并从中返回0)。

您的双倍值是888.4834966,但当您使用:时

cout << "Double number:t" << number << endl << endl;

它使用双精度的默认值,手动设置使用:

cout << "Double number:t" << std::setprecision(10) << number << endl << endl;

输出的精度可能只是没有显示number中的所有数据。有关如何设置输出精度的格式,请参阅此链接。