C++ 文件 IO : read input of "29.0" to double but output is "29", 即 ".0"已删除

标签 c++ io double

我使用以下代码从文件中读取数据。 输入文件是

29.0 45.0 0.0 15.0

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    string fileName;
    cout << "input the file: ";
    cin >> fileName;

    double temp1=0.0, temp2=0.0, temp3=0.0, temp4=0.0;

    ifstream fin;
    fin.open(fileName.c_str());

    if(!fin.is_open()){
        cout << "Could not open file" << endl; 
    }

    fin >> temp1 >>temp2 >>temp3 >>temp4;

    cout << temp1 << " " << temp2 << " " << temp3 <<" " <<temp4 <<endl;
    fin.close();
}

但我得到的是 29 45 0 15 而不是 29.0 45.0 0.0 15.0

如果我将数据文件更改为 29.1 45.1 0.1 15.1,那么我得到的正是 29.1 45.1 0.1 15.1

有人知道为什么会这样吗?

最佳答案

如果您想保留“.0”等当且仅当它出现在输入中时,您需要将值作为文本读取 - 例如到 std::string 中。当您读入 double 时,将存储逻辑值(在准确的文本值在 double 中没有按位表示的情况下,会尽可能地存储它,比如不能准确表示的 0.1),输出代码会猜测您想要多少位数字 - 默认情况下,它会猜测尾随的“.0”对读者没有任何值(value)。

您可以使用像 std::fixed 这样的 io 操纵器来更改它和 std::setprecision - 两个页面都有有用的示例,setprecision 为方便起见复制如下:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
    const long double pi = std::acos(-1.L);
    std::cout << "default precision (6): " << pi << '\n'
              << "std::precision(10):    " << std::setprecision(10) << pi << '\n'
              << "max precision:         "
              << std::setprecision(std::numeric_limits<long double>::digits10 + 1)
              << pi << '\n';
}

输出:

default precision (6): 3.14159
std::precision(10):    3.141592654
max precision:         3.141592653589793239

关于C++ 文件 IO : read input of "29.0" to double but output is "29", 即 ".0"已删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292646/

相关文章:

c++ - 如何在变量中设置浮点精度

c - 在输入行中间使用 EOF?

java - 获取 CSV 格式的 Excel 数据

c++ - C++ 中的除法

c# - 将字符串转换为 double

java - 具有双坐标的多边形

c++ - 如何禁用 QTextEdit 中的光标?

c++ - 将 VS 8.0 lib 文件与 VS 6.0 链接

c++ - GCC 5.3 : -fno-semantic-interposition 中的新选项

parsing - Haskell readLn 没有解析错误