伙计们!我已经为这个问题苦苦挣扎了一段时间,到目前为止我还没有找到任何解决方案。
在下面的代码中,我用数字初始化了一个字符串。然后我使用 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/