【问题标题】:(C++) std::istringstream reads up to 6 digits from string to double(C++) std::istringstream 从字符串读取最多 6 位数字到双精度
【发布时间】:2013-07-10 20:25:02
【问题描述】:

伙计们!我一直在努力解决这个问题,但到目前为止我还没有找到任何解决方案。

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

#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 个。如何将所有字符串加载到 double 变量中?

【问题讨论】:

  • instr.str(test);之前尝试instr.precision(8)

标签: c++ istringstream sstream


【解决方案1】:
#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)。

【讨论】:

    【解决方案2】:

    你的 double 值是 888.4834966 但是当你使用时:

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

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

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

    【讨论】:

      【解决方案3】:

      您的输出精度可能只是没有显示number 中的所有数据。请参阅此link,了解如何格式化输出精度。

      【讨论】:

      • 标准输入法不使用precision()
      猜你喜欢
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多