c++ - (C++) std::istringstream 从字符串读取最多 6 位数字到 double

标签 c++ istringstream sstream

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

在下面的代码中,我用数字初始化了一个字符串。然后我使用 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 个。如何将所有字符串加载到 double 变量中?

最佳答案

#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)。

关于c++ - (C++) std::istringstream 从字符串读取最多 6 位数字到 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17580241/

相关文章:

c++ - 为什么 OpenGL 不在这段代码中绘制多边形?

c++ - C++如何在同一行中cin和cout?

C++:字符串流解析

c++ - 修改 istringstream 中的变量数

c++ - 在嵌入式系统上将数组排序函数从 C++ 移植到 C

c++ - 什么是指针的正确无效值?

c++ - 使用带有 '>>' 运算符的 std::istringstream 的奇怪行为

c++ - 为什么这个 extern "C"函数不能使用 python ctypes?

c++ - 根据类型标记字符串流

c++ - 使用 istringstream 的问题