(C++)std::istringstream从字符串到双精度最多可读取6位数字
(C++) std::istringstream reads up to 6 digits from string to double
各位!我已经为这个问题挣扎了一段时间,到目前为止我还没有找到任何解决方案
在下面的代码中,我用一个数字初始化一个字符串。然后我使用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
中的所有数据。有关如何设置输出精度的格式,请参阅此链接。
相关文章:
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 如何从文件中读取数字并在数组中使用它们?
- 使用模板化函数从CSV文件中读取数字
- 根据数字在 c++ 中作为矩阵的位置从文件中读取数字
- 如何从文件中读取数字序列?
- 如何允许我的程序成功读取数字包含的文件
- 如何仅从C 中的文本文件中读取数字
- 从没有分隔符 C++ 的文件读取数字出现次数
- 读取数字并转换为单词
- 从文件,特定行中仅读取数字
- 从TextFile中读取数字,并检查它们是否在范围内
- C 从文本文件中读取数字,忽略注释
- 从文件读取数字列表到动态数组
- 我正在尝试从文件中读取数字
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- C++如何从文件中读取数字并将其分配到数组中的相应位置
- 读取数字的文本文件,并存储在C++的整数数组中
- 从文件中读取数字
- 从文本中读取数字并输出平均值