C++ - 从文件读取到双

标签 c++ readfile

<分区>

我对编程还比较陌生,目前正在学习 C++ 类(class)。到目前为止,我还没有遇到任何重大问题。我正在制作一个程序,其中 X 数量的评委可以得分 0.0 - 10.0(双倍),然后删除最高和最低的分数,然后计算并打印出平均值。

这部分已经完成,现在我想从一个文件中读取以下形状的文件: 示例.txt - 10.0 9.5 6.4 3.4 7.5

但我遇到了点 (.) 的问题以及如何绕过它以使数字变成 double 。有什么建议和(好的)解释可以让我理解吗?


TL;DR:从文件(例如“9.7”)读取一个 double 变量以放入数组。

最佳答案

由于您的文本文件是用空格分隔的,您可以利用默认情况下跳过空格的std::istream 对象(在本例中,std::fstream):

#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>

int main() {
    std::ifstream ifile("example.txt", std::ios::in);
    std::vector<double> scores;

    //check to see that the file was opened correctly:
    if (!ifile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);//exit or do additional error checking
    }

    double num = 0.0;
    //keep storing values from the text file so long as data exists:
    while (ifile >> num) {
        scores.push_back(num);
    }

    //verify that the scores were stored correctly:
    for (int i = 0; i < scores.size(); ++i) {
        std::cout << scores[i] << std::endl;
    }

    return 0;
}

注意:

强烈建议尽可能使用 vectors 代替动态数组,原因有很多,如下所述:

When to use vectors and when to use arrays in C++?

关于C++ - 从文件读取到双,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885876/

相关文章:

c++ - 不支持 GLSL 330 内核

c++ - 如何在 C++ 生成器中包含 exe 文件?

c++ - 选择 3D 游戏引擎

C++如何从文件中读取以进行计数控制循环?

c++ - 苹果 LLVM 5.0 pragma 优化

python - 为什么我的 Python 读取的位数比我设置的位数多?

javascript - 从本地文件运行时 $.get() 无法正常工作

c++ - 如何读写文件

python - 从文件中读取字符串的特定区域

c - 如何使用双指针从文本文件填充字符串数组?