除了使用 getline() 和使用字符串流转换之外,还有什么其他方法可以从 ifstream 读取双倍

What are other ways to read double from an ifstream besides using getline() and converting with stringstream?

本文关键字:方法 其他 什么 ifstream 读取 getline 字符串 转换      更新时间:2023-10-16

我已经编写了以下内容来从输入文件中读取双精度,但这似乎很麻烦,我还可以使用什么其他方法?我应该注意哪些优点/缺点?

我认为这种方法是最准确的,因为不应该有任何二进制<>十进制转换问题,对吗?

#include<string>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
void Stats::fill()
{
    string temp;
    stringstream convert;
    statFile.open("statsinput.txt");
    for(int i = 0; i<maxEntries && !statFile.eof(); i++)
    {
        getline(statFile, temp);
        convert<<temp;
        convert>>stats[i];
    }
    statFile.close();
}

直接在文件中使用输入运算符?

for(int i = 0; i<maxEntries && statFile >> stats[i]; i++)
    ;

请记住,所有输入流都继承自相同的基类,因此您可以对流(如 stringstream)或cin所有其他输入流执行的所有操作

如果你有现代C++(C++11)编译器,你可以使用std::stof,std::stod或std::stelled函数。

然后你可以写:

 getline(statFile, temp);
 double d = std::stod(temp);

有关C++参考页面的更多信息

相关文章: